MRO (Method Resolution Order) Demo
Show how Python resolves methods in a multiple inheritance hierarchy using MRO.
IntermediateTopic: Object-Oriented Programs
Python MRO (Method Resolution Order) Demo Program
This program helps you to learn the fundamental structure and syntax of Python programming.
# Program to demonstrate method resolution order (MRO)
class A:
def who_am_i(self):
print("I am A")
class B(A):
def who_am_i(self):
print("I am B")
class C(A):
def who_am_i(self):
print("I am C")
class D(B, C):
pass
d = D()
d.who_am_i()
print(D.mro())Output
I am B [<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>]
Understanding MRO (Method Resolution Order) Demo
D inherits from B and C; Python uses the MRO list to decide which 'who_am_i' implementation to call.
Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.