0
0
PythonConceptBeginner · 3 min read

What is MRO in Python: Method Resolution Order Explained

In Python, MRO stands for Method Resolution Order, which is the order Python follows to look for methods in a class hierarchy. It determines which method is called first when multiple classes are involved in inheritance.
⚙️

How It Works

Imagine you have a family tree of classes, where some classes inherit from others. When you call a method on an object, Python needs to decide which class's method to use if multiple classes have the same method name. This decision is made using the MRO.

The MRO is like a roadmap Python follows to find the right method. It starts from the class of the object and moves through its parent classes in a specific order until it finds the method. This order is carefully designed to avoid confusion and conflicts, especially when multiple inheritance is involved.

Python uses an algorithm called C3 linearization to create this order, ensuring that subclasses come before their parents and that the order respects the inheritance relationships.

💻

Example

This example shows how Python decides which method to call using MRO when multiple classes have the same method name.

python
class A:
    def greet(self):
        return "Hello from A"

class B(A):
    def greet(self):
        return "Hello from B"

class C(A):
    def greet(self):
        return "Hello from C"

class D(B, C):
    pass

obj = D()
print(obj.greet())
print(D.__mro__)
Output
Hello from B (<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)
🎯

When to Use

You use MRO automatically whenever you work with classes that inherit from multiple parents in Python. It helps you understand which method will run when you call it on an object.

Knowing the MRO is especially useful when you design complex class hierarchies or use multiple inheritance, so you can predict and control method behavior. It helps avoid bugs caused by unexpected method calls.

For example, if you create a class that inherits from two or more classes that have methods with the same name, understanding MRO lets you know which method Python will pick.

Key Points

  • MRO defines the order Python looks for methods in a class hierarchy.
  • It is important in multiple inheritance to avoid confusion about which method runs.
  • Python uses the C3 linearization algorithm to create the MRO.
  • You can see the MRO of a class using the __mro__ attribute or the mro() method.

Key Takeaways

MRO determines the order Python searches for methods in inheritance.
It is crucial for understanding behavior in multiple inheritance scenarios.
Use the __mro__ attribute or mro() method to inspect the method resolution order.
Python’s MRO uses C3 linearization to maintain a consistent and logical order.