How does multiple inheritance and the Method Resolution Order work in Python?

· Category: Python Programming

Short answer

Python supports multiple inheritance using the C3 linearization algorithm to determine the Method Resolution Order (MRO). The MRO defines the order in which base classes are searched for methods. Use ClassName.__mro__ or mro() to inspect it.

Steps

  1. Define a class that inherits from multiple parents.
  2. Use super() to delegate to the next class in the MRO.
  3. Inspect .__mro__ to understand the resolution order.
class A:
    def method(self):
        print("A.method")

class B(A):
    def method(self):
        print("B.method")
        super().method()

class C(A):
    def method(self):
        print("C.method")
        super().method()

class D(B, C):
    def method(self):
        print("D.method")
        super().method()

d = D()
d.method()
print(D.__mro__)

Tips

  • super() follows the MRO, not just the direct parent, which avoids duplicate initialization in diamond hierarchies.
  • Mixins are small classes designed to be combined with others through multiple inheritance.
  • Keep multiple inheritance shallow and favor composition when the hierarchy becomes confusing.

Common issues

  • Incompatible method signatures in parent classes cause TypeError when super() chains through them.
  • Circular or ambiguous inheritance graphs raise a TypeError at class definition time.
  • Overlooking the MRO leads to methods being called in an unexpected order.