Try it here
Subscribe
Python MRO : Method Resolution Order

Python Multiple Inheritance

python_multiple_inheritance

Multiple Inheritance

Multiple Python inheritance are when a class inherits from multiple base classes.

class Employee:
    pass
class Programmer:
    pass
class Developer(Employee, Programmer):
    pass

print(issubclass(Developer,Employee))
print(issubclass(Developer,Programmer))
==========================================================================================
True
True

Method Resolution Order(MRO)

When we search for an attribute in a class that is involved in python multiple inheritance, an order is followed. First, it is searched in the current class. If not found, the search moves to parent classes. This is left-to-right, depth-first.

So, in the above class, the search order will be – Developer, Employee, Programmer, Object.

This order is called linearization of class Developer, and the set of rules applied are called MRO (Method Resolution Order). To get the MRO of a class, you can use either the __mro__ attribute or the mro() method.

>>> print(Developer.__mro__)
(<class '__main__.Developer'>, <class '__main__.Employee'>, <class '__main__.Programmer'>, <class 'object'>)

The __mro__ attribute returns a tuple, but the mro() method returns a python list.

>>> print(Developer.mro())
[<class '__main__.Developer'>, <class '__main__.Employee'>, <class '__main__.Programmer'>, <class 'object'>]

In MRO, It will check for the good head(which means does the current class inheriting from any of the classes which are called later, If yes then they will not be added to the current search list).

Check Python inheritance

Writer profile pic

Neha on Sep 20, 2020 at 01:09 am


This article is contributed by Neha. If you like dEexams.com and would like to contribute, you can write your article here or mail your article to admin@deexams.com . See your article appearing on the dEexams.com main page and help others to learn.



Post Comment

Comments( 0)

×

Forgot Password

Please enter your email address below and we will send you information to change your password.