6.1. 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.1.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.say_hello()
Admin login

6.1.2. Override Init

  • __init__() is inherited as any other method

  • Child class will override parent's __init__() method

>>> 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.1.3. Override Class Variables

  • Class variables are inherited as any other attribute

  • Child class will override parent's class variable

>>> class User:
...     group = 'users'
>>>
>>> class Admin(User):
...     group = 'admins'

Using this class variable will use the child's field:

>>> mark = Admin()
>>> mark.group
'admins'

6.1.4. Override Instance Variables

  • Instance variables are inherited as any other attribute

  • Child __init__() method will override the parent's __init__() method

  • Child class will override parent's instance variable

>>> class User:
...     def __init__(self):
...         self.group = 'user'
>>>
>>>
>>> class Admin(User):
...     def __init__(self):
...         self.group = 'admins'
>>>
>>>
>>> mark = Admin()
>>> vars(mark)
{'group': 'admins'}

6.1.5. Assignments