Object-oriented programming · lesson 7 of 17
Parts in this lesson
Aclass AudioBook(LibraryItem, Recording):two parents
Bclass JsonMixin:one skill, for any class
CBook.__mro__the order Python searches
Dsuper()the next class in the MRO
Eisinstance4.5: is it one of these?

Multiple inheritance and the MRO

Last updated

An audiobook is a library item, and it's also a recording with a running time. Python lets a class have more than one parent, so it can be both. In this lesson you'll give a class two parents, mix small skills into classes with mixins, see the order Python searches for a method, find out where super() really goes, and meet the diamond, where two parents share a parent of their own.

By the end of this lesson you can

  • Write a class with two parents, and a mixin that adds one skill to any class
  • Read a class's method resolution order with __mro__, and say which method runs
  • Explain why super() goes to the next class in the MRO, not always the parent
  • Read the error Python gives when parents are listed in an order it can't use

Two parents

An audiobook is a library item, with a title and a year. It's also a recording, with a running time. Put both parents in the brackets, separated by a comma, and the child inherits from both. Having more than one parent is called multiple inheritance.

Step 1 code main.py
Edit the code, then run it again
  • Lines 10 to 12: Recording has one method, length(), which turns minutes into hours and minutes with // and %.
  • Line 15 gives AudioBook two parents.
  • Line 22 uses a method from the first parent, and line 23 one from the second.
  • Line 24: the audiobook counts as both.

Every class has a __name__: its name as text. Line 25 uses it to show the two parents, from __bases__ in lesson 4.5, as a list of names.

Notice that Recording reads self.minutes, but never sets it. It counts on the class it's part of to do that, as AudioBook does on line 18.

Mixins

Recording isn't much use on its own: it's a skill waiting for a class to join. A small class like that, with a few methods and no __init__, is called a mixin. Its name usually ends in Mixin, and you add it to any class that needs the skill.

Here are two. JsonMixin turns an object into JSON text. json.dumps is json.dump from lesson 2.8 without the file: it gives the JSON back as text. PrintableMixin prints an object as a card, one attribute to a line.

Step 2 code main.py
Edit the code, then run it again
  • Lines 4 to 6 and 9 to 12 are the two mixins. They use vars(self), so they work on any object, whatever its attributes are.
  • Line 21: Book gets both skills. Line 27: DVD gets only one.
  • Lines 33 and 34 use them.

The mixins come first in the brackets, and the real parent last. That's the usual order. The next step shows why the order matters.

A mixin is written once and used by classes that have nothing else in common. A Member could use JsonMixin too, without being a library item.

The method resolution order

When two parents both have a method with the same name, which one runs? Here LibraryItem and PrintableMixin both have describe(). Book and DVD list the same two parents in opposite orders.

Step 3 code main.py
Edit the code, then run it again

Python works out, once for each class, the list of classes it searches, in order. That list is the method resolution order, or MRO. It's kept in the class's __mro__, and lines 25 and 26 print it as names.

For Book, PrintableMixin comes before LibraryItem, so its describe() wins on line 23. For DVD, it's the other way round. Python builds the MRO from three rules:

How Python orders the classes
RuleExample
A child comes before its parentsBook before LibraryItem
Parents keep the order they’re written in the bracketsclass Book(PrintableMixin, LibraryItem): PrintableMixin first
Every class appears onceobject is last, once, however many paths lead to it

It's the search from lesson 4.6, written down: child first, then the parents, left to right. When you're not sure which method will run, print the MRO.

super() follows the MRO

In lesson 4.5, super() meant "my parent class". That was true while each class had one parent. The full rule is: super() means the next class in the MRO of the object's own class.

Both mixins here extend describe() with super(). NewMixin puts new: in front, and UpperMixin makes it all capitals.

Step 4 code main.py
Edit the code, then run it again

Line 12 is in NewMixin, whose only parent is object. object has no describe(), yet line 12 works. That's because the object is a Book, and in Book's MRO on line 25, the class after NewMixin is UpperMixin. Its super() on line 17 goes on to LibraryItem.

So the calls run down the MRO: NewMixin asks UpperMixin, which asks LibraryItem. Then the answers come back up: LibraryItem gives Emma (1815), UpperMixin makes it capitals, and NewMixin adds new:.

Swap the two mixins on line 20 and run it again. Now new: is added first and made capitals with the rest: NEW: EMMA (1815).

The diamond

Now an AudioBook whose two parents, Book and Recording, share a parent of their own, LibraryItem. Drawn out, the four classes make a diamond shape. Each __init__ prints its name, then calls super().__init__.

The diamond: two parents that share a grandparent
100%
LibraryItem
  • +title: str
  • +__init__(title: str)
Book
  • +__init__(title: str)
Recording
  • +__init__(title: str)
AudioBook
  • +__init__(title: str)
  • Class LibraryItem; attributes: title; methods: __init__.
  • Class Book; inherits from LibraryItem; no attributes of its own; methods: __init__.
  • Class Recording; inherits from LibraryItem; no attributes of its own; methods: __init__.
  • Class AudioBook; inherits from Book and Recording; no attributes of its own; methods: __init__.
Step 5 code main.py
Edit the code, then run it again

LibraryItem.__init__ ran once, even though both Book and Recording lead to it. The MRO on line 26 lists every class once, and each super() goes to the next one in the list. So Book's super() on line 10 goes to Recording, not to LibraryItem, and Recording's goes on to LibraryItem.

If Book wrote LibraryItem.__init__(self, title) instead of using super(), Recording.__init__ would be skipped. That's why Python code calls super(), not the parent by name.

This works smoothly here because every __init__ in the family takes the same values. When they don't, it gets harder. That's one reason mixins usually have no __init__ at all, and why most classes keep to one real parent plus a few mixins.

Parents in an impossible order

Here AudioBook lists LibraryItem first and Book second. Press Run and read the error.

Step 6 code main.py
Edit the code, then run it again

Nothing printed. Python stopped on line 9, while making the class, because it couldn't build an MRO for it. Two of the rules from step 3 disagree:

  • The brackets put LibraryItem before Book.
  • Book is a child of LibraryItem, so Book must come before it.

No order can follow both rules, so Python won't make the class. The last line of the error names the two parents it couldn't place.

To fix it, put the child first: class AudioBook(Book, LibraryItem):. Better still, write only class AudioBook(Book):. LibraryItem comes with Book anyway.

In other languages

This step is optional. It's for anyone who will meet Java or Rust later.

More than one parent in three languages
PythonJavaRust
More than one parent classYesNo: one parent class, but any number of interfacesNo parent classes. A type can implement any number of traits
Mixing in a skillA mixin class, listed as a parentAn interface with default methods comes closeA trait with default methods
Two parents with the same methodThe first in the MRO winsIf two interfaces give the same default method, the class must write its ownYou say which trait you mean: Display::fmt(&x, f)
What super meansThe next class in the MROThe parent classDoesn’t arise

C# works like Java: one parent class, and any number of interfaces, which can have default methods.

Java and C# chose one parent class so that the diamond can't happen with classes. Rust has no parents at all, and builds shared behaviour from traits. Simple Rust 4.3 shows traits with default methods, which do the job of mixins.

Check what you learned

Three questions. Pick or type an answer, then check it.

What does this program print?
class A:
    def hello(self):
        return "A"


class B:
    def hello(self):
        return "B"


class C(B, A):
    pass


print(C().hello())
A class is written class Book(NewMixin, UpperMixin, LibraryItem):. Where does super() inside NewMixin go, for a book?
Why does class AudioBook(LibraryItem, Book): fail, when Book is a child of LibraryItem?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Python