How does class variables function in multi-inheritance Python classes?


A class can be derived from more than one base classes in Python. This is called multiple inheritance.

In multiple inheritance, the features of all the base classes are inherited into the derived class. The syntax for multiple inheritance is similar to single inheritance.

class Super1:
    pass
class Super2:
    pass
class MultiDerived(Super1, Super2):
   pass

In the multiple inheritance scenario, any specified attribute is searched first in the current class. If not found, the search continues into parent classes in depth-first, left-right fashion without searching same class twice.

So, in the above example of MultiDerived class the search order is [MultiDerived, Super1, Super2, object]. This order is also called linearization of MultiDerived class and the set of rules used to find this order is called Method Resolution Order (MRO).

MRO ensures that a class always appears before its parents and in case of multiple parents, the order is same as tuple of base classes.

MRO of a class can be viewed as the __mro__ attribute or mro() method. The former returns a tuple while latter returns a list.

>>> MultiDerived.mro()
[<class '__main__.MultiDerived'>,
 <class '__main__.Super1'>,
 <class '__main__.Super2'>,
 <class 'object'>]

Updated on: 16-Jun-2020

318 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements