[PYTHON] Class inheritance and super functions

python


class Car(object):
    def __init__(self, model=None):
        self.model = model
    def run(self):
        print('run')

class ToyotaCar(Car):
    def run(self):
        print('run fast')

class TeslaCar(Car):
    def __init__(self, model='Model A', enable_auto_run=False):
        super().__init__(model)
        self.enable_auto_run = enable_auto_run
    def run(self):
        print('run very fast')
    def auto_run(self):
        print('auto run')

car = Car()
car.run()

print('############')

toyota_car = ToyotaCar('Lexus')
print(toyota_car.model)
toyota_car.run()

print('############')

tesla_car = TeslaCar('Model S')
print(tesla_car.model)
tesla_car.run()
tesla_car.auto_run()

Execution result


run
############
Lexus
run fast
############
Model S
run very fast
auto run

The constructor of the TeslaCar class is Originally

python


def __init__(self, model='S Model', enable_auto_run=False):
        self.model = model
        self.enable_auto_run = enable_auto_run

I'm about to write It does the same thing as the superclass constructor, so It can be written using the super function.

Recommended Posts

Class inheritance and super functions
Comparison of class inheritance and constructor description
Trouble with Python pseudo-private variables and class inheritance
About Class and Instance
Higher-order functions and decorators
Method overriding and super
[Python] Class inheritance, override
Class methods and static methods
Anonymous and map functions
Various class methods and static methods
Python: Class and instance variables
Python class variables and instance variables
[python] super (), inheritance, __init__, etc.
Python 3 sorted and comparison functions
Python higher-order functions and comprehensions
[Day 7] Template inheritance and include
Avoid implementing useless functions with inheritance
I'll inherit and override the class
[Python of Hikari-] Chapter 09-03 Class (inheritance)
Python class definitions and instance handling
Formulas and functions (updated as appropriate)
I looked into class inheritance overrides.
Calculation of homebrew class and existing class
perl objects and python class part 1.
Understand Armijo's rules and convex functions
Tips for replacing and debugging functions