← Back to Python, page 3

python-0044 · Medium mid

What is the method resolution order, and how does super() behave with multiple inheritance?

The MRO is the order in which Python searches classes for an attribute, computed with C3 linearisation; it keeps subclasses before parents and preserves the order of bases. super() calls the next class in the MRO of the object's type, not simply the parent, which is what makes cooperative multiple inheritance work.

Full answer
python
class Base:
    def greet(self): return ["Base"]
class Left(Base):
    def greet(self): return ["Left"] + super().greet()
class Right(Base):
    def greet(self): return ["Right"] + super().greet()
class Child(Left, Right):
    def greet(self): return ["Child"] + super().greet()

print([c.__name__ for c in Child.__mro__])
print(Child().greet())
print(Left().greet())

Output:

text
['Child', 'Left', 'Right', 'Base', 'object']
['Child', 'Left', 'Right', 'Base']
['Left', 'Base']

For Child, the MRO is Child, Left, Right, Base, object. Inside Left.greet, super() therefore calls Right.greet, not Base.greet, even though Left's parent is Base. Each class appears once, so Base runs exactly once. For a plain Left instance, the MRO is Left, Base, object, and the same super() call reaches Base. Cooperative classes must all call super() and accept compatible arguments (often **kwargs) for this to work.

python
class Base:
    def greet(self): return ["Base"]
class Left(Base):
    def greet(self): return ["Left"] + super().greet()
class Right(Base):
    def greet(self): return ["Right"] + super().greet()
class Child(Left, Right):
    def greet(self): return ["Child"] + super().greet()

print([c.__name__ for c in Child.__mro__])
print(Child().greet())
print(Left().greet())

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • MRO uses C3 linearisation
  • super() follows the instance's MRO
  • Each class appears once
  • Cooperative classes all call super()
  • Bases order matters

Common mistakes

  • Calling Parent.method(self) directly in diamond hierarchies
  • Assuming super() means the parent

Follow-ups

  • When does C3 linearisation fail?
  • What are mixins?

Tips

  • Print __mro__ first