Method Resolution Order #
In Python, Method Resolution Order (MRO) refers to the order in which methods are searched for and resolved in a class hierarchy, especially when multiple inheritance is involved. Understanding MRO is crucial for correctly determining which implementation of a method will be used when there are overlapping method names in the inheritance chain.
Here's an example to demonstrate MRO in multiple inheritance:
class A:
def method(self):
return "A"
class B(A):
def method(self):
return "B"
class C(A):
def method(self):
return "C"
class D(B, C):
pass
d = D()
print(d.method()) # Output: "B"
In the example above, class D inherits from both class B and class C, which in turn inherit from class A. The MRO for class D is D -> B -> C -> A, following the order of inheritance. When the method() is invoked on an instance of class D, the MRO is consulted, and the leftmost occurrence of the method in the MRO (B) is used.
We can inspect the class property __mro__ to see the MRO of the class. For example:
print(D.__mro__) # Output: (<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)
You will see the order of resolution main.D -> main.B -> main.C -> main.A in the output.
Exercise #
- Switch the inheritance order in line 14 to get the desired output.
Tests #
D().method()should return"C"- Do not change the implementation of the classes
A,B,C, andD - Class
Dmust inherit from classesA,B, andC
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules