What is the Method Resolution Order (MRO) in Python, and how does it work with multiple inheritance?
The MRO is the order in which Python searches a class and its parents for an attribute. It uses C3 linearization: children come before parents, and the order of bases you wrote is kept. You can see it with ClassName.__mro__ or mro().
Explain it simply
When you ask a family for a recipe, you first ask the child, then the parents, and you never ask a grandparent before both of their children have been asked. In multiple inheritance, C3 produces one consistent line-up that obeys that rule, so every class is looked at once and in a predictable order.
Example
class A:
def hello(self):
return "A"
class B(A):
def hello(self):
return "B"
class C(A):
def hello(self):
return "C"
class D(B, C):
pass
print(D().hello()) # Output: B
print([k.__name__ for k in D.__mro__]) # Output: ['D', 'B', 'C', 'A', 'object']This is the diamond problem. A appears only once, and after both B and C. super() follows this same order, which is why cooperative multiple inheritance works.
What to say in the interview
"The MRO is the lookup order for attributes and methods, computed by C3 linearization. It keeps subclasses before bases and preserves the left-to-right order of the base list. super() walks the MRO, not just the direct parent. Inconsistent hierarchies raise a TypeError at class creation."
Common mistakes
- Thinking
super()always means "the parent class". It means "next in the MRO".