Introduction to Python ProgrammingXYZ Homework Edition

⇩ 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.

Adapted from Introduction to Python Programming by OpenStax (openstax.org), licensed under CC BY-NC-SA 4.0. Changes were made. License: CC-BY-NC-SA-4.0.

These eBooks are a prerelease and are not yet certified conformant with WCAG 2.1 AA or ADA Title II. Every page is built against an automated accessibility gate, and the published editions will meet ADA Title II requirements when they release in late September 2026. If something is unusable, please tell us.