Sobes.tech
Junior — Middle

How does the mechanism of method and attribute lookup and resolution work in Python's multiple inheritance?

sobes.tech AI

Answer from AI

In Python, method and attribute lookup in multiple inheritance is performed using the Method Resolution Order (MRO) algorithm. MRO determines the order in which Python searches for attributes in classes.

Key points:

  • MRO is constructed using the C3 linearization algorithm, which provides a consistent and predictable order.
  • When accessing a method or attribute, Python first looks in the object itself, then in the class of the object, and then in the parent classes according to the MRO.

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"
print(D.mro())  # Shows the search order: [D, B, C, A, object]

Thus, Python searches for the method sequentially in classes D, B, C, A, and then in the base object.