the full guide

Multiple inheritance and MRO

Multiple inheritance lets a class have several parents. The Method Resolution Order (MRO) is the fixed order in which Python searches those classes for an attribute. It's computed with the C3 algorithm, and super() follows it.

8 min Advanced

What you need: The earlier topics of this module, and its prerequisites.

Definition

Multiple inheritance lets a class have several parents. The Method Resolution Order (MRO) is the fixed order in which Python searches those classes for an attribute. It's computed with the C3 algorithm, and super() follows it.

In simple words

If you ask a question and both parents could answer, who goes first? The MRO is the family's agreed order, so the answer is always the same.

Why it matters

Frameworks use small mixin classes this way, and bugs can arise when you don't know which method actually runs.

How it works

In code

mro.py
class Base:
    def hello(self):
        return "Base"

class Left(Base):
    def hello(self):
        return "Left > " + super().hello()

class Right(Base):
    def hello(self):
        return "Right > " + super().hello()

class Child(Left, Right):
    pass

print(Child().hello())
print([cls.__name__ for cls in Child.__mro__])

Output

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

Common mistakes

  • Assuming super() means the parent. It means the next class in the MRO, which can be a sibling.
  • Calling parent methods by name, like Left.hello(self), so that some classes run twice.

Check yourself

Question 1

1. For class C(A, B), which is searched first?

Question 2

2. What does super() follow?

Summary

  • The MRO decides which method runs.
  • Check it with Class.__mro__.
  • Keep inheritance shallow.

Finished reading?

Sources: The Python Tutorial, python.org