Python MRO (Method Resolution Order) โ OOP Guide
Understand MRO (Method Resolution Order) in Python OOP. Learn how Python resolves method calls in multiple inheritance using C3 linearization with examples.
๐ง What is MRO?
MRO stands for Method Resolution Order. It defines the order in which Python looks for methods and attributes in a hierarchy of classes when you use super().
๐ช Why is MRO Needed?
Consider a "diamond inheritance" like this:
A
/ \
B C
\ /
D
- All classes eventually inherit from
A. - Without MRO, Python could accidentally call
Amultiple times โ causing bugs. - MRO ensures that each classโs method (like
__init__) is called once, and in a predictable order.
๐ How MRO Works
Python uses the C3 Linearization Algorithm to compute MRO.
class A:
def __init__(self):
print("A initialized")
class B(A):
def __init__(self):
super().__init__()
print("B initialized")
class C(A):
def __init__(self):
super().__init__()
print("C initialized")
class D(B, C):
def __init__(self):
super().__init__() # Initializes B -> C -> A
print("D initialized")
d = D() # Output order might surprise beginners๐ฆ Class Definitions
class A:
def __init__(self):
print("A initialized")- Base class
A. It prints a message when initialized.
class B(A):
def __init__(self):
super().__init__()
print("B initialized")- Class
Binherits fromA. - It calls
super().__init__(), which refers toA.__init__.
class C(A):
def __init__(self):
super().__init__()
print("C initialized")- Similarly,
Cinherits fromA.
class D(B, C):
def __init__(self):
super().__init__() # MRO applies here
print("D initialized")Dinherits from bothBandC. This is where MRO kicks in.
๐คฏ What Happens When You Call d = D()?
When we create an instance of D, the following happens:
- Python looks at the MRO (Method Resolution Order) of class
D. Dinherits fromBandC, and both inherit fromA. So Python uses C3 linearization to resolve this.
To see the MRO:
print(D.mro())Output:
[<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>]This means:
- Start at
D - Then look in
B - Then
C - Then
A - Finally,
object(the root class of all Python classes)
๐ ๏ธ How super() Uses MRO
When you call super().__init__() inside D, Python uses the MRO list:
- It goes to the next class after
Dโ thatโsB B'ssuper()calls the next one โCC'ssuper()calls the next โAAdoesnโt usesuper(), so it ends there
No class is repeated, and the initialization flows down this path.
๐ Final Output Order:
A initialized
C initialized
B initialized
D initializedExplanation:
D.__init__โB.__init__โC.__init__โA.__init__- Then the print statements in reverse order as the stack unwinds.
๐ Summary
- MRO ensures consistency in how classes are searched.
super()follows the MRO chain.- You can always check MRO with:
ClassName.mro()orhelp(ClassName) - MRO prevents the diamond problem by avoiding multiple calls to the same base class.