Python Classes and Objects · Lesson 93 of 149

Python Multiple Inheritance and MRO

What you will learn

  • Writing a class with several parents
  • The diamond problem and the MRO
  • How super() really works
  • Cooperative __init__ methods
  • Mixins: small add-on classes
  • Conflicts and when to avoid multiple inheritance

1. Several parents

A class may list more than one parent in the parentheses:

class Fly:
    def move(self):
        return "fly"

class Swim:
    def move(self):
        return "swim"

class Duck(Fly, Swim):
    pass

class Duck2(Swim, Fly):
    pass

print(Duck().move(), Duck2().move())
fly swim

Both parents define move, so which one wins? The first parent listed: Duck(Fly, Swim) finds Fly.move first. The order you write the parents matters.

2. The diamond problem

The tricky case is when the parents share a grandparent, forming a diamond:

      A
     / \
    B   C
     \ /
      D
class A:
    def hi(self):
        return "A"

class B(A):
    def hi(self):
        return "B>" + super().hi()

class C(A):
    def hi(self):
        return "C>" + super().hi()

class D(B, C):
    def hi(self):
        return "D>" + super().hi()

print(D().hi())
D>B>C>A

Each hi calls super().hi(), and the result visits D, B, C, A, once each. Notice that after B, the next call went to C (a sibling), not straight to A. How does Python decide this order?

Quick check: in `class D(B, C)`, which parent is searched first?

B, the first one listed.

3. The method resolution order

Every class has a method resolution order (MRO): the list of classes Python searches, in order, to find an attribute. See it with __mro__ or .mro():

print([k.__name__ for k in D.__mro__])
print(D.__bases__)
['D', 'B', 'C', 'A', 'object']
(<class '__main__.B'>, <class '__main__.C'>)

The rules (Python uses the C3 linearization algorithm) come down to this:

  1. A class comes before its parents.
  2. Parents are kept in the order written in the class line.
  3. Every class appears once, and a shared grandparent such as A comes after all the classes that inherit from it.
  4. object is always last.

Swapping the parents changes the order:

class E(C, B):
    pass

print([k.__name__ for k in E.__mro__])
print(E().hi())
['E', 'C', 'B', 'A', 'object']
C>B>A

Some orders are impossible to satisfy, and Python refuses to build the class:

class X(A, B):
    pass
TypeError: Cannot create a consistent method resolution order (MRO) for bases A, B

A is a parent of B, so B must come before A, but the line says A first. Write class X(B, A) instead (the more specific class first).

4. What super() really does

super() does not mean "my parent". It means "the next class in the MRO of the object's type". That is why B's super().hi() called C when the object was a D: in D's MRO, C comes right after B.

Because every hi uses super(), the chain runs through all classes exactly once. This is called cooperative inheritance, and it works only if every class in the chain uses super(). If one class calls a parent by name (A.hi(self)), the chain can run a class twice or skip some. Here are two classes that both call a shared base by name:

class Base:
    def __init__(self):
        print("Base init")

class L(Base):
    def __init__(self):
        Base.__init__(self)
        print("L")

class M(Base):
    def __init__(self):
        Base.__init__(self)
        print("M")

class N(L, M):
    def __init__(self):
        L.__init__(self)
        M.__init__(self)

N()
Base init
L
Base init
M

Base.__init__ ran twice. With super() throughout, it would run once.

5. Cooperative init

When several classes each have their own __init__, make each one:

  1. take the arguments it needs plus **kwargs,
  2. pass the rest on with super().__init__(**kwargs):
class Root:
    def __init__(self, **kw):
        print("Root", kw)

class P(Root):
    def __init__(self, a, **kw):
        print("P", a)
        super().__init__(**kw)

class Q(Root):
    def __init__(self, b, **kw):
        print("Q", b)
        super().__init__(**kw)

class R(P, Q):
    def __init__(self, a, b):
        super().__init__(a=a, b=b)

R(1, 2)
P 1
Q 2
Root {}

P takes a and forwards the rest (b) to the next class in the MRO, which is Q, not Root. Each class takes its own and passes on the leftovers. The base Root receives an empty kw. Use keyword arguments here, since positions would be mixed up.

6. Mixins

A mixin is a small class that adds one ability and is not meant to be used alone. You "mix" it into other classes, usually listing mixins first:

import json

class JsonMixin:
    def to_json(self):
        return json.dumps(self.__dict__)

class ReprMixin:
    def __repr__(self):
        args = ", ".join(f"{k}={v!r}" for k, v in vars(self).items())
        return f"{type(self).__name__}({args})"

class Person(JsonMixin, ReprMixin):
    def __init__(self, name, age):
        self.name, self.age = name, age

p = Person("Rina", 25)
print(p)
print(p.to_json())
Person(name='Rina', age=25)
{"name": "Rina", "age": 25}

Mixins are the respectable use of multiple inheritance: each is tiny, has no __init__ of its own, and does one thing.

A mixin can also wrap a method of whatever comes after it, using super():

class Timestamped:
    def save(self):
        print("stamp")
        super().save()

class Store:
    def save(self):
        print("save to disk")

class Doc(Timestamped, Store):
    pass

Doc().save()
print([k.__name__ for k in Doc.__mro__])
stamp
save to disk
['Doc', 'Timestamped', 'Store', 'object']

Timestamped has no parent that defines save, yet super().save() works, because the next class in Doc's MRO is Store. Used alone, Timestamped().save() would fail, which is why it is a mixin.

7. Guidelines

Do Do not
use mixins: small, focused, no state build deep diamonds with big classes
use super() everywhere in a cooperative chain call parents by name in some places and super() in others
put the more specific class first list a parent before its own child
check ClassName.__mro__ when unsure guess the order
prefer composition (lesson 13.9) when you only need to reuse code inherit from several big classes

Many programmers avoid multiple inheritance outside mixins, and other languages leave it out entirely. In Python it is safe when used with care.

Worked example: a saving pipeline built from mixins

A Record must be validated, audited and then saved. Each step is a mixin that does its part and calls super().save(). The MRO decides the order, and reordering the parents reorders the steps.

class Base:
    def save(self):
        return ["saved"]


class Validated:
    def save(self):
        if not self.name:
            raise ValueError("name is required")
        return ["validated"] + super().save()


class Audited:
    def save(self):
        return ["audited"] + super().save()


class Record(Audited, Validated, Base):
    def __init__(self, name):
        self.name = name


print(Record("Rina").save())
print([c.__name__ for c in Record.__mro__])

try:
    Record("").save()
except ValueError as e:
    print("ValueError:", e)


class Plain(Validated, Base):
    def __init__(self, name):
        self.name = name


print(Plain("Sam").save())
['audited', 'validated', 'saved']
['Record', 'Audited', 'Validated', 'Base', 'object']
ValueError: name is required
['validated', 'saved']
Part Role
Base.save the real work, last in the chain
Validated, Audited mixins that add a step and pass on with super()
Record(Audited, Validated, Base) the parent order is the step order
Plain(Validated, Base) a different mix: no audit step, with no code change in the mixins

Note that Validated uses self.name, which it expects the final class to provide: mixins often rely on attributes of the classes they join, so document that. The names are made up.

Common mistakes

  • Parents in the wrong order, causing a "Cannot create a consistent MRO" error.
  • Mixing super() with direct parent calls, which runs a class twice or skips one.
  • Thinking super() means "the parent". It means the next class in the MRO.
  • Forgetting **kwargs in cooperative __init__ methods, so arguments are lost.
  • Mixins with their own state and __init__, which makes them hard to combine.
  • Assuming a method comes from a particular parent without looking at the MRO.

Key takeaways

  • class D(B, C) inherits from both; lookups follow the MRO, shown by D.__mro__.
  • The MRO puts each class before its parents, keeps the written order, and lists every class once.
  • super() means "next in the MRO", so use it consistently to make a cooperative chain where every class runs once.
  • For cooperative __init__, take what you need plus **kwargs and pass the rest on.
  • Mixins are the safe, common use; otherwise prefer composition.

Practice

1. What does D.__mro__ show?

Show answer

The tuple of classes Python searches, in order, when looking up an attribute on D (ending with object).

2. In class Duck(Fly, Swim), both define move. Which runs?

Show answer

Fly.move, because Fly comes first in the MRO.

3. Why does class X(A, B) fail when B inherits from A?

Show answer

A parent cannot come before its own child in the MRO. Write class X(B, A).

4. What does super() return in a method of B when the object is a D?

Show answer

A proxy for the next class after B in D's MRO (for D(B, C) that is C), not necessarily B's own parent.

5. What is a mixin?

Show answer

A small class that adds one ability (such as to_json) to other classes through inheritance, and is not meant to be used on its own.

6. Why take **kwargs in cooperative __init__ methods?

Show answer

So each class can take the arguments it needs and pass the rest to the next class in the MRO with super().__init__(**kwargs), whichever class that happens to be.