MRO (Method Resolution Order) Demo in Python

ClassName.__mro__ is the lookup order. Print it when diamond inheritance gets weird.

IntermediateObject-Oriented ProgramsExample 24 of 25
mro-method-resolution-order-demo.py
Run in browser
1# Program to demonstrate method resolution order (MRO)
2
3class A:
4 def who_am_i(self):
5 print("I am A")
6
7class B(A):
8 def who_am_i(self):
9 print("I am B")
10
11class C(A):
12 def who_am_i(self):
13 print("I am C")
14
15class D(B, C):
16 pass
17
18d = D()
19d.who_am_i()
20print(D.mro())

Output

I am B
[<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>]

What's going on

D inherits from B and C; Python uses the MRO list to decide which 'who_am_i' implementation to call.