Object-oriented programming · 11 / 26 Theory

Multiple inheritance, MRO and composition

Inheritance is a powerful tool that can be misused. This article covers the advanced cases and when another option is better.

Multiple inheritance and MRO

In Python a class can inherit from several: class D(B, C). When several base classes define the same method, Python decides the order with the MRO (*method resolution order*), a list that can be inspected with D.__mro__. With super() the next one in that list is called, which is not necessarily the direct base.

class A:
    def hello(self):
        return "A"

class B(A):
    def hello(self):
        return "B" + super().hello()

class C(A):
    def hello(self):
        return "C" + super().hello()

class D(B, C):
    def hello(self):
        return "D" + super().hello()

print(D().hello())                          # DBCA
print([k.__name__ for k in D.__mro__])     # ['D', 'B', 'C', 'A', 'object']

In the example, each class calls super(), so they are all chained (in the “diamond” class A runs only once).

Mixins: reusable behavior

A mixin is a small class that provides a specific behavior and is not used alone, but mixed with others through multiple inheritance.

class TextMixin:
    def to_text(self):
        return ", ".join(f"{k}={v}" for k, v in vars(self).items())

class Person(TextMixin):
    def __init__(self, name, age):
        self.name, self.age = name, age

print(Person("Ann", 30).to_text())        # name=Ann, age=30

Composition versus inheritance

Inheritance expresses “is a” (a manager *is an* employee). Composition expresses “has a” (a car *has an* engine): the object stores another object and delegates work to it. It is usually more flexible, because components can be changed without altering the hierarchy.

class Engine:
    def start(self):
        return "vroom"

class Car:                      # un coche TIENE un engine (composición)
    def __init__(self):
        self.engine = Engine()

    def start(self):
        return self.engine.start()

print(Car().start())         # vroom
  • Use inheritance when there really is an “is a” relationship and the subclass can be used wherever the base is expected.
  • Use composition when you only want to reuse functionality.
  • Avoid deep hierarchies: more than two or three levels are hard to follow.
  • With multiple inheritance, keep the base classes independent (mixins) and all of them with super().

You practice inheritance and polymorphism in Employee hierarchy, and designing a data type with controlled operations in Stack as a class.