6.3. Inheritance Override
Child inherits all fields and methods from parent
Used to avoid code duplication
- override
When child has method or attribute with the same name as parent. In such case child attribute will be used (will overload parent).
6.3.1. Override Method
Child class will override parent's method
>>> class User:
... def login(self):
... print('User login')
>>>
>>> class Admin(User):
... def login(self):
... print('Admin login')
Calling this method will use the child's method:
>>> mark = Admin()
>>> mark.login()
Admin login
6.3.2. Override Init
__init__()
is inherited as any other methodChild class will override parent's
__init__()
methodWarning: Call to
__init__
of super class is missed
>>> class User:
... def __init__(self):
... print('User init')
>>>
>>> class Admin(User):
... def __init__(self):
... print('Admin init')
Calling this method will use the child's method:
>>> mark = Admin()
Admin init
6.3.3. Override Class Variables
Class variables are inherited as any other attribute
Child class will override parent's class variable
>>> class User:
... ROLE = 'user'
>>>
>>> class Admin(User):
... ROLE = 'admin'
Using this class variable will use the child's field:
>>> mark = Admin()
>>> mark.ROLE
'admin'
6.3.4. Override Instance Variables
Instance variables are inherited as any other attribute
Child
__init__()
method will override the parent's__init__()
methodChild class will override parent's instance variable
>>> class User:
... def __init__(self):
... self.role = 'user'
>>>
>>> class Admin(User):
... def __init__(self):
... self.role = 'admin'
>>>
>>>
>>> mark = Admin()
>>> mark.role
'admin'