liveBook · Manning

Multiple inheritance

As explained in Practices of the Python Pro

Multiple inheritance is an inheritance mechanism in which a class derives from more than one parent class.

Multiple inheritance lets a class derive from two or more parent classes. Python uses it to combine related behaviors, often through small mixins that act like interfaces. This can avoid a deep hierarchy, while composition remains a better fit for has-a relationships. section 3.5

Combining behavior with mixins

A Dog can inherit from SpeakMixin and RollOverMixin, gaining both speak() and roll_over() without placing every possible animal trick in one hierarchy. section 3.5

When parents define the same method, Python follows the method resolution order (MRO). It searches classes in a calculated order, and super() continues that search rather than simply calling one fixed parent. Inspect the result with Class.__mro__. section 8.3.3

Liger and method resolution

Liger inherits from Lion and Tiger. Its super().eats() call finds Lion first, then Liger adds more prey to the returned list. The resulting order follows Liger, Lion, Tiger, BigCat, and object. section 8.3.3

Listing 3.4. Multiple inheritance providing interface-like behavior
class SpeakMixin:                            #1
    def speak(self):
        name = self.__class__.__name__.lower()
        print(f'The {name} says, "Hello!"')

class RollOverMixin:                         #2
    def roll_over(self):
        print('Did a barrel roll!')

class Dog(SpeakMixin, RollOverMixin):        #3
    pass

Use the short Python listing to see interface-like behavior assembled from two mixins. section 3.5

How Practices of the Python Pro covers it

How deep it goes
Explains mixins, super(), and MRO calculation, including class ordering and inspection, while deferring deeper inheritance concepts.
Examples
Demonstrates dog behavior mixins and a Liger hierarchy whose prey methods expose MRO behavior.
What it assumes
Assumes basic classes and inheritance while introducing interfaces, mixins, composition, and MRO progressively.
What you can do after
Apply it via Python mixins, predict super() lookup, and inspect a class's method resolution order.
How it connects
Connects multiple inheritance with composition, interfaces, mixins, duck typing, super(), and method resolution order.

Also explained in

Compare how 4 books explain multiple inheritance →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Practices of the Python Pro. The section links point to the parts of the book it draws on.