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.
- Lines 10 to 12:
Recordinghas one method,length(), which turns minutes into hours and minutes with//and%. - Line 15 gives
AudioBooktwo 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.
- 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:
Bookgets both skills. Line 27:DVDgets 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.
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:
| Rule | Example |
|---|---|
| A child comes before its parents | Book before LibraryItem |
| Parents keep the order they’re written in the brackets | class Book(PrintableMixin, LibraryItem): PrintableMixin first |
| Every class appears once | object 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.
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__.
- +title: str
- +__init__(title: str)
- +__init__(title: str)
- +__init__(title: str)
- +__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__.
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.
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
LibraryItembeforeBook. Bookis a child ofLibraryItem, soBookmust 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.
| Python | Java | Rust | |
|---|---|---|---|
| More than one parent class | Yes | No: one parent class, but any number of interfaces | No parent classes. A type can implement any number of traits |
| Mixing in a skill | A mixin class, listed as a parent | An interface with default methods comes close | A trait with default methods |
| Two parents with the same method | The first in the MRO wins | If two interfaces give the same default method, the class must write its own | You say which trait you mean: Display::fmt(&x, f) |
What super means | The next class in the MRO | The parent class | Doesn’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.
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.
- The Python Tutorial: Multiple Inheritance: left to right, and the diamond
- The Python Language Reference: type.__mro__
- Built-in Functions: super: super() searches the classes after this one in the MRO
- Glossary: method resolution order
- The Python 2.3 Method Resolution Order: how Python builds the MRO, for the curious
- OMG Unified Modeling Language (UML) 2.5.1: the standard the class diagrams follow
- The Java Tutorials: Multiple Inheritance of State, Implementation, and Type: one parent class, many interfaces in Java
- The Java Tutorials: Default Methods: interfaces that bring code, and two with the same method
- The Rust Programming Language: Traits: Defining Shared Behavior: a Rust type with many traits