Junior — Middle
How is attribute search performed when using multiple inheritance in Python?
sobes.tech AI
Answer from AI
In Python, when using multiple inheritance, attribute lookup follows the MRO (Method Resolution Order) algorithm. This is an ordered list of classes that Python constructs using the C3 linearization algorithm. When accessing an attribute, Python searches for it in the classes according to the MRO, starting from the current class, then in the parent classes, until it finds the attribute or exhausts the list.
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
obj = D()
obj.method() # Will print "B" because B appears before C in D's MRO
print(D.mro()) # Shows the search order: [D, B, C, A, object]
Thus, attribute lookup in multiple inheritance is strictly deterministic and predictable.