Middle
What is MRO (Method Resolution Order)?
sobes.tech AI
Answer from AI
MRO (Method Resolution Order) determines the order in which Python searches for methods and attributes in the class inheritance hierarchy.
In Python 3, the C3 Superclass Linearization Algorithm is used to determine the MRO.
- Single inheritance: The order is straightforward - first the current class, then its parent, then the parent's parent, and so on.
- Multiple inheritance: The C3 algorithm ensures monotonicity (the order of parent classes does not change relative to each other) and local precedence order (the order of a class and its immediate ancestors is preserved).
You can view the MRO using:
- The
__mro__attribute: a tuple of classes in resolution order. - The
mro()method: returns a list of classes in resolution order. - The
help()function: displays the MRO in class information.
Example:
class A:
def method(self):
print("Method from A")
class B(A):
def method(self):
print("Method from B")
class C(A):
def method(self):
print("Method from C")
class D(B, C):
pass
# D.__mro__
# Output: (<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)
# d = D()
# d.method()
# Output: Method from B
In this example, the MRO for class D is D -> B -> C -> A -> object. When calling d.method(), Python first looks for it in D (not found), then in B (found), and executes the method from B.
Understanding the MRO is critical when working with multiple inheritance to predict code behavior.