Multiple Inheritance in Python

Learn how Python utilizes MRO for multiple inheritance, and how multiple inheritance enables mixins.

We'll cover the following

Python supports multiple inheritance. Because inheritance, when improperly used, leads to design problems, we could also expect that multiple inheritance will also yield even bigger problems when it's not correctly implemented.

Multiple inheritance is, therefore, a double-edged sword. It can also be very beneficial in some cases. Just to be clear, there is nothing wrong with multiple inheritance—the only problem it has is that when it's not implemented correctly, it will multiply the problems.

Multiple inheritance is a perfectly valid solution when used correctly, and this opens up new patterns and mixins. Perhaps one of the most powerful applications of multiple inheritance is that which enables the creation of mixins. So before exploring mixins, we need to understand how multiple inheritance works and how methods are resolved in a complex hierarchy.

Method resolution order (MRO)

Some people don't like multiple inheritance because of the constraints it has in other programming languages, for instance, the so-called diamond problem. When a class extends from two or more classes, and all of those classes also extend from other base classes, the bottom ones will have multiple ways to resolve the methods coming from the top-level classes. The question is: which of these implementations is used?

Consider the following diagram, which has a structure with multiple inheritance. The top-level class has a class attribute and implements the __str__ method. Think of any of the concrete classes, for example, ConcreteModuleA12—it extends from BaseModule1 and BaseModule2, and each one of them will take the implementation of __str__ from BaseModule. Which of these two methods is going to be the one for ConcreteModuleA12?

Get hands-on with 1200+ tech skills courses.