Sobes.tech
Junior — Middle

How is method resolution order (MRO) used to find methods in multiple inheritance in Python?

sobes.tech AI

Answer from AI

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

Key points:

  • Python uses the C3 linearization algorithm to compute the MRO.
  • When a method is called, Python first searches for it in the class itself, then in the parent classes in the order defined by the MRO.
  • This helps avoid ambiguities and conflicts in multiple inheritance.

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 method search order

Here, the method is found in class B because the MRO for D is [D, B, C, A, object].

Thus, MRO guarantees a predictable and unambiguous order of method lookup in multiple inheritance.