Login
📚 Introduction to Python Programming
Chapters ▾
⇩ Download ▾

13.5 Multiple inheritance and mixin classes

Learning objectives

By the end of this section you should be able to

  • Construct a class that inherits from multiple superclasses.
  • Identify the diamond problem within multiple inheritance.
  • Construct a mixin class to add functionality to a subclass.

Multiple inheritance basics

Multiple inheritance is a type of inheritance in which one class inherits from multiple classes. A class inherited from multiple classes has all superclasses listed in the class definition inheritance list. Ex: class SubClass(SuperClass_1, SuperClass_2).

The diamond problem and mixin classes

Multiple inheritance should be implemented with care. The diamond problem occurs when a class inherits from multiple classes that share a common superclass. Ex: Dessert and BakedGood both inherit from Food, and ApplePie inherits from Dessert and BakedGood.

A conceptual diagram illustrating a classification hierarchy. 'ApplePie' is shown as a subtype of both 'Dessert' and 'BakedGood', which in turn are both subtypes of 'Food'.
Figure 13.2 The diamond problem. If both Dessert and BakedGood override a Food method, the overridden Food method that ApplePie inherits is ambiguous. Thus, diamond shaped inheritance should be avoided.

Mixin classes promote modularity and can remove the diamond problem. A mixin class:

  • Has no superclass
  • Has attributes and methods to be added to a subclass
  • Isn't instantiated (Ex: Given MyMixin class, my_inst = MyMixin should never be used.)

Mixin classes are used in multiple inheritance to add functionality to a subclass without adding inheritance concerns.