6.11. OOP Inheritance Overload¶
Child inherits all fields and methods from parent
Used to avoid code duplication
- overload¶
When child has method or attribute with the same name as parent. In such case child attribute will be used (will overload parent).
6.11.1. Overload Method¶
>>> class Person:
... def say_hello(self):
... print('Hello')
>>>
>>>
>>> class Astronaut(Person):
... def say_hello(self):
... print('Howdy')
>>>
>>>
>>> astro = Astronaut()
>>> astro.say_hello()
Howdy
6.11.2. Overload Init¶
>>> class Person:
... def __init__(self):
... print('Person init')
>>>
>>>
>>> class Astronaut(Person):
... pass
>>>
>>>
>>> astro = Astronaut()
Person init
>>> class Person:
... def __init__(self):
... print('Person init')
>>>
>>>
>>> class Astronaut(Person):
... def __init__(self):
... print('Astronaut init')
>>>
>>>
>>> astro = Astronaut()
Astronaut init
6.11.3. Overload ClassVars¶
>>> class Person:
... firstname = 'Mark'
... lastname = 'Watney'
... job = None
>>>
>>>
>>> class Astronaut(Person):
... job = 'astronaut'
>>>
>>>
>>> astro = Astronaut()
>>>
>>> astro.firstname
'Mark'
>>> astro.lastname
'Watney'
>>> astro.job
'astronaut'
6.11.4. Overload Attribute¶
>>> class Person:
... def __init__(self):
... self.firstname = 'Mark'
... self.lastname = 'Watney'
... self.job = None
>>>
>>>
>>> class Astronaut(Person):
... def __init__(self):
... self.job = 'astronaut'
>>>
>>>
>>> astro = Astronaut()
>>> vars(astro)
{'job': 'astronaut'}