Using Python super() for multiple inheritance
Super in Python¶
With the super() builtin, we can easily work with multiple inheritance and avoid referring to the base class explicitly.
Single Inheritence¶
In [56]:
class Name:
def __init__(self, your_name):
print('{} is awesome (1)'.format(your_name))
class SecondName(Name):
def __init__(self, first_name, other_name):
print('{} is awesome (2)'.format(first_name))
super().__init__(other_name)
In [57]:
call_classes = SecondName('John', 'Doe')
By instantiating SecondName
, it automatically instantiates Name
with super()
.
Multiple Inheritence¶
In [58]:
class Name:
def __init__(self, your_name):
print('{} is awesome (1)'.format(your_name))
class SecondName(Name):
def __init__(self, first_name, second_name):
print('{} is awesome (2)'.format(second_name))
super().__init__(first_name)
class ThirdName(SecondName):
def __init__(self, first_name, second_name, third_name):
print('{} is awesome (3)'.format(third_name))
super().__init__(first_name, second_name)
In [59]:
call_classes = SecondName('Tom', 'Dick')
In [60]:
call_classes = ThirdName('Tom', 'Dick', 'Harry')
By instantiating ThirdName
once, it automatically instantiates SecondName
then ThirdName
with super()
.
Checking Method Resolution Order (MRO)¶
We can double check the order of instantiations with by checking the MRO with __mro__
.
In [61]:
ThirdName.__mro__
Out[61]:
In [62]:
print(ThirdName.__mro__[0])
print(ThirdName.__mro__[1])
print(ThirdName.__mro__[2])
print(ThirdName.__mro__[3])
In [65]:
SecondName.__mro__
Out[65]:
In [66]:
print(SecondName.__mro__[0])
print(SecondName.__mro__[1])
print(SecondName.__mro__[2])
In [67]:
Name.__mro__
Out[67]:
In [68]:
print(SecondName.__mro__[0])
print(SecondName.__mro__[1])