Junior — Middle
Could you explain the working principle of the MRO mechanism in the context of multiple inheritance in Python?
sobes.tech AI
Answer from AI
MRO (Method Resolution Order) is the order in which Python searches for methods and attributes in classes during multiple inheritance.
When a class inherits from multiple parents, MRO determines the order in which Python will traverse these classes to find the required method.
Python uses the C3 linearization algorithm to compute the MRO, which guarantees:
- A linear and predictable traversal order
- Preservation of the inheritance order specified in the class definition
- No conflicts or cycles
Example:
class A:
def method(self):
print("A")
class B(A):
def method(self):
print("B")
class C(A):
def method(self):
print("C")
class D(B, C):
pass
D().method() # Will print "B"
print(D.mro()) # Shows the class traversal order
Here, Python first searches for the method in D, then in B, then in C, and finally in A.