Skip to content
devtoolbox.cc

Python · Chapter 12 of 21

Python inheritance, composition, protocols and operators

15 min study · Examples checked with Python 3.14 and 3.15 ·

The previous chapter built single classes. This one is about how classes relate to each other and to the language. Inheritance creates specialized versions of a class. Composition builds objects out of other objects. Protocols, the special methods behind +, len(), in and for, let your own types behave like built-in ones. Knowing when to use which matters more than the syntax, so each section says when the tool fits.

Subclasses and super()

A subclass inherits everything from its base class and can add to it or replace parts of it:

class Lesson:
    def __init__(self, title: str, minutes: int):
        self.title = title
        self.minutes = minutes

    def describe(self) -> str:
        return f"{self.title} ({self.minutes} min)"

class VideoLesson(Lesson):
    def __init__(self, title: str, minutes: int, url: str):
        super().__init__(title, minutes)
        self.url = url

    def describe(self) -> str:
        return "Video: " + super().describe()

for lesson in [Lesson("Loops", 15), VideoLesson("Classes", 20, "https://example.com/v/1")]:
    print(lesson.describe())
# Loops (15 min)
# Video: Classes (20 min)
print(isinstance(VideoLesson("x", 1, ""), Lesson), VideoLesson.__mro__[1].__name__)  # True Lesson

VideoLesson overrides describe and calls the original through super(). The loop doesn’t care which kind of lesson it has; each object runs its own version of the method. That is polymorphism, and it is the main reason to inherit.

super() does not simply mean “the parent class”. It means “the next class in the method resolution order” (__mro__), which matters once a class has several bases. With multiple inheritance, every class in the chain must call super() with compatible arguments, so keep it for small mixin classes that add one capability.

A subclass must keep the promises of its base class. If code works with any Lesson, it must also work with a VideoLesson. An override that rejects inputs the base accepted, or returns a different kind of value, breaks callers even though Python raises no error.

Prefer composition when the relationship is “has a”

Inheritance says “is a”: a video lesson is a lesson. Many relationships are “has a” or “uses a”, and those are better modelled by storing one object inside another:

class PlainText:
    def heading(self, text: str) -> str:
        return text.upper()

class Markdown:
    def heading(self, text: str) -> str:
        return f"## {text}"

class Report:
    def __init__(self, formatter):
        self.formatter = formatter

    def render(self, titles: list[str]) -> str:
        return "\n".join(self.formatter.heading(t) for t in titles)

print(Report(Markdown()).render(["Python", "Django"]))
# ## Python
# ## Django

A report has a formatter; it is not one. Swapping formatters needs no subclass, and tests can pass in a fake formatter. Neither formatter inherits from anything: the report only needs an object with a heading method. This is duck typing (“if it walks like a duck…”), and it is how most Python code works.

Describe the interface: ABC or Protocol

When you want the required methods written down, there are two options.

from abc import ABC, abstractmethod
from typing import Protocol

class Exporter(ABC):
    @abstractmethod
    def export(self, rows: list[dict]) -> str: ...

class CsvExporter(Exporter):
    def export(self, rows: list[dict]) -> str:
        return "\n".join(",".join(map(str, r.values())) for r in rows)

class Formatter(Protocol):
    def heading(self, text: str) -> str: ...

def title_block(f: Formatter, text: str) -> str:
    return f.heading(text)

print(CsvExporter().export([{"a": 1, "b": 2}]))   # 1,2
try:
    Exporter()
except TypeError as error:
    print(type(error).__name__)                   # TypeError

An abstract base class (ABC) is a real base class: subclasses must inherit from it, and Python refuses to create an object while any @abstractmethod is unimplemented. A Protocol is checked only by type checkers. Any class with a matching heading method satisfies Formatter, without inheriting from it, so title_block(Markdown(), "x") passes a type check. Use a Protocol to describe what a function needs from its argument, and an ABC when you also want to share code or enforce the contract at runtime.

Operator overloading

Special methods map operators to your class: __add__ for +, __eq__ for ==, __lt__ for <, __bool__ for truth testing, and so on.

from dataclasses import dataclass

@dataclass(frozen=True)
class Duration:
    minutes: int

    def __add__(self, other):
        if not isinstance(other, Duration):
            return NotImplemented
        return Duration(self.minutes + other.minutes)

    def __bool__(self) -> bool:
        return self.minutes > 0

total = Duration(45) + Duration(30)
print(total, bool(Duration(0)))            # Duration(minutes=75) False
print(sum([Duration(5), Duration(10)], Duration(0)))  # Duration(minutes=15)

Returning the special value NotImplemented for an unsupported operand tells Python to try the other operand’s reversed method (__radd__) and, if that fails too, to raise a clear TypeError, so Duration(5) + 3 fails properly. Don’t confuse it with the NotImplementedError exception. sum starts from 0 unless you give a start value; passing Duration(0) lets it add durations.

Equality and hashing go together: objects that compare equal must have the same hash, and an object’s hash must not change while it sits in a set or is used as a dictionary key. Frozen dataclasses handle both for you. Only add operators whose meaning is obvious in your domain; adding two durations makes sense, adding two learners doesn’t.

Container protocols: len, in, indexing and for

A class becomes usable with len(), in, square brackets and for loops by implementing __len__, __contains__, __getitem__ and __iter__:

class Playlist:
    def __init__(self, titles):
        self._titles = list(titles)

    def __len__(self):
        return len(self._titles)

    def __contains__(self, title):
        return title in self._titles

    def __getitem__(self, index):
        return self._titles[index]

    def __iter__(self):
        return iter(self._titles)

playlist = Playlist(["Variables", "Loops", "Functions"])
print(len(playlist), "Loops" in playlist, playlist[-1], playlist[:2])
# 3 True Functions ['Variables', 'Loops']
print(", ".join(playlist))   # Variables, Loops, Functions

Each method delegates to the list inside, so negative indexes and slices work without extra code. The class still controls its public surface: there is no append, so callers cannot add titles behind its back. The collections.abc module provides base classes such as Sequence and Mapping that fill in the remaining methods (index, count, __reversed__) once you implement the core ones.

Practice

Add a QuizLesson(Lesson) with a questions count whose describe() extends the base text with the number of questions. Then try Duration(10) + 5 and Duration(10) == Duration(10), and predict the results first.

Answer check: QuizLesson("Loops quiz", 10, 5).describe() could return Loops quiz (10 min), 5 questions, built with super().describe(). Duration(10) + 5 raises TypeError because both sides return NotImplemented; the equality is True, since dataclasses compare fields.

Summary

Inherit for real “is a” relationships, call super(), and keep the base class’s promises. Prefer composition for “has a”. Document required methods with typing.Protocol or enforce them with an ABC. Implement special methods only where their meaning is natural, return NotImplemented for unsupported operands, and delegate container protocols to a built-in collection.

All Python chapters