In this lesson, you will learn how Python’s Method Resolution Order (MRO) navigates complex inheritance trees to ensure predictable method execution.
The Problem of Multiple Inheritance
When a class inherits from multiple parents, conflicts can arise if those parents share a common ancestor or define methods with the same name. Without a strict rule, Python wouldn't know which version of a method to execute. Python solves this using the C3 Linearization algorithm, which calculates a specific, stable path through the class hierarchy.
How to Observe the MRO
Every class in Python has a special attribute called __mro__ (or a method named .mro()) that reveals the exact sequence in which Python searches for methods. The rule is simple: Python searches from left to right, bottom to top, ensuring that a class always appears before its parents, and that base classes are visited only after all subclasses are exhausted.
Consider this diamond-shaped hierarchy:
class A:
def greet(self): return "A"
class B(A):
def greet(self): return "B"
class C(A):
def greet(self): return "C"
class D(B, C):
pass
# Checking the resolution order
print(D.mro())
# Output: [D, B, C, A, object]
In this example, when you call D().greet(), Python finds B's implementation first. Because B is listed before C in the inheritance definition class D(B, C), Python prioritizes B's logic. Even though both B and C inherit from A, the MRO ensures A is only visited at the very end, preventing redundant calls or ambiguous state changes.
Best Practices for Predictability
To manage complex hierarchies effectively:
- Prefer Mixins: Use classes designed only to add specific behaviors rather than full stateful objects.
- Use
super(): Always usesuper()instead of calling parent methods by name.super()is MRO-aware; it automatically calculates which class to visit next in the sequence, allowing you to build cooperative chains of method calls that respect the hierarchy.
Key Takeaway: Python’s MRO provides a predictable, left-to-right search path that resolves method conflicts by ensuring subclasses are always prioritized over their parents.