DEV Community

Cover image for Python Multiple Inheritance – Python MRO (Method Resolution Order) in 1 minute
Mangabo Kolawole
Mangabo Kolawole Subscriber

Posted on • Originally published at Medium

7 2

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

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.😁

Heroku

Deliver your unique apps, your own way.

Heroku tackles the toil — patching and upgrading, 24/7 ops and security, build systems, failovers, and more. Stay focused on building great data-driven applications.

Learn More

Top comments (0)

Image of Quadratic

Free AI chart generator

Upload data, describe your vision, and get Python-powered, AI-generated charts instantly.

Try Quadratic free

👋 Kindness is contagious

If this post resonated with you, feel free to hit ❤️ or leave a quick comment to share your thoughts!

Okay