Sobes.tech
Middle

How are methods resolved in Python with multiple inheritance (MRO)?

sobes.tech AI

Answer from AI

In Python, the method resolution order (MRO) in multiple inheritance is determined by the C3 linearization algorithm. It constructs a linear order of classes that respects the inheritance order and ensures consistency.

When a method is called, Python searches for it in the object's class, then in the parent classes in the order defined by 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

d = D()
 d.method()  # Will print "B"
print(D.mro())  # Shows the method search order

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

Thus, the MRO guarantees a predictable and unambiguous method search order in multiple inheritance.

How are methods resolved in Python with multiple… - sobes.tech