Junior — Middle
Explain the principle of determining the order of method calls in multiple inheritance in Python 2.
sobes.tech AI
Answer from AI
In Python 2, the order of method calls in multiple inheritance is determined by the C3 linearization algorithm, which forms the class sequence (MRO — Method Resolution Order).
How it works:
- For new-style classes (inheriting from
object), C3 linearization is used. - MRO is constructed to preserve the inheritance order while resolving conflicts and avoiding ambiguities.
- When a method is called, Python searches for it in classes according to the MRO from left to right.
Example:
class A(object):
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 = D()
d.method() # Prints "B"
print(D.__mro__)
Here, the method is called from class B, because the MRO for D will be (D, B, C, A, object).
For old-style classes (not inheriting from object), a different algorithm is used — depth-first search from left to right, which can lead to ambiguities.