Using Python super() for multiple inheritance
Python Super

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')
John is awesome (2)
Doe is awesome (1)

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')
Dick is awesome (2)
Tom is awesome (1)
In [60]:
call_classes = ThirdName('Tom', 'Dick', 'Harry')
Harry is awesome (3)
Dick is awesome (2)
Tom is awesome (1)

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]:
(__main__.ThirdName, __main__.SecondName, __main__.Name, object)
In [62]:
print(ThirdName.__mro__[0])
print(ThirdName.__mro__[1])
print(ThirdName.__mro__[2])
print(ThirdName.__mro__[3])
<class '__main__.ThirdName'>
<class '__main__.SecondName'>
<class '__main__.Name'>
<class 'object'>
In [65]:
SecondName.__mro__
Out[65]:
(__main__.SecondName, __main__.Name, object)
In [66]:
print(SecondName.__mro__[0])
print(SecondName.__mro__[1])
print(SecondName.__mro__[2])
<class '__main__.SecondName'>
<class '__main__.Name'>
<class 'object'>
In [67]:
Name.__mro__
Out[67]:
(__main__.Name, object)
In [68]:
print(SecondName.__mro__[0])
print(SecondName.__mro__[1])
<class '__main__.SecondName'>
<class '__main__.Name'>
Tags: python