Python Multiple Inheritance – Python MRO (Method Resolution Order) in 1 minute

Mangabo Kolawole - May 20 '22 - - Dev Community

Python is a highly Oriented-Object Language. It means that everything in Python is an object, making it relatively easy to build OOP logic with Python.

If you are doing Multiple Inheritance, you should know of Python Method Resolution Order.
Before diving into the concept, let's quickly remind you how to write a class with multiple parent classes.

To make a class inherit from multiple python classes, we write the names of these classes inside the parentheses to the derived class while defining it.

We separate these names with commas.

class Animal:
    pass

class Bird:
    pass

class Duck(Animal, Bird):
    pass
Enter fullscreen mode Exit fullscreen mode

Let's explain Python MRO now.

Python MRO (Method Resolution Order)

An order is followed when looking for an attribute in a class involved in multiple inheritances.

Firstly, the search starts with the current class. The search moves to parent classes from left to right if not found.

Let's retake the example and add some attributes.

class Animal:
    pass

class Bird:
    bird_type = "wings"

class Duck(Animal, Bird):
    pass

duck = Duck()
Enter fullscreen mode Exit fullscreen mode

duck.bird_type will look first in Duck, then Animal, and finally Bird.

Duck => Animal => Bird

To get the MRO of a class, you can use either the mro attribute or the mro() method.

Duck.mro()
[<class '__main__.Duck'>, <class '__main__.Animal'>, <class '__main__.Bird'>, <class 'object'>]
Enter fullscreen mode Exit fullscreen mode

If you have some questions regarding the concept, feel free to add comments.😁

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player