0
0
Pythonprogramming~5 mins

Method Resolution Order (MRO) in Python

Choose your learning style9 modes available
Introduction
Method Resolution Order (MRO) decides the order in which Python looks for methods in classes when you use inheritance. It helps Python know which method to run when multiple classes have methods with the same name.
When you have a class that inherits from more than one parent class.
When you want to understand which method will run if multiple parents have the same method name.
When debugging why a certain method is called in a complex class hierarchy.
When designing classes that share behavior and want to control method lookup order.
Syntax
Python
class Child(Parent1, Parent2):
    pass

# To see MRO:
print(Child.__mro__)
The MRO is a tuple showing the order Python checks classes for methods.
Python uses the C3 linearization algorithm to create the MRO.
Examples
Shows MRO for class C which inherits from B, which inherits from A.
Python
class A:
    def greet(self):
        print('Hello from A')

class B(A):
    def greet(self):
        print('Hello from B')

class C(B):
    pass

print(C.__mro__)
Shows MRO for class Z with multiple inheritance from X and Y.
Python
class X:
    def greet(self):
        print('Hello from X')

class Y:
    def greet(self):
        print('Hello from Y')

class Z(X, Y):
    pass

print(Z.__mro__)
Sample Program
Class D inherits from B and C. We print the MRO to see the order Python looks for methods. Then we call greet() to see which method runs.
Python
class A:
    def greet(self):
        print('Hello from A')

class B(A):
    def greet(self):
        print('Hello from B')

class C(A):
    def greet(self):
        print('Hello from C')

class D(B, C):
    pass

print('MRO of D:', D.__mro__)

obj = D()
obj.greet()
OutputSuccess
Important Notes
The MRO helps avoid confusion when multiple parents have the same method.
The order in the class definition (e.g., class D(B, C)) affects the MRO.
You can always check MRO using ClassName.__mro__ or help(ClassName).
Summary
MRO decides the order Python looks for methods in inheritance.
It is important for multiple inheritance to know which method runs.
You can check MRO with ClassName.__mro__ to understand method lookup.