Python operations as interfaces

Lesson 19 of 19 · Python Object Design

Python’s built-in operations are interfaces too. Special methods, often called dunder methods because their names begin and end with double underscores, let a class participate in operations such as +, print, and comparisons. __init__ is one you have already met.

class Duration:
    def __init__(self, minutes):
        self.minutes = minutes

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

    def __str__(self):
        return f"{self.minutes} min"

    def __repr__(self):
        return f"Duration({self.minutes!r})"

    def __eq__(self, other):
        if not isinstance(other, Duration):
            return NotImplemented
        return self.minutes == other.minutes

    def __lt__(self, other):
        if not isinstance(other, Duration):
            return NotImplemented
        return self.minutes < other.minutes

a, b = Duration(15), Duration(20)
print(a + b)
print(repr(a))
print(a == Duration(15))
print(a < b)
print(a == "15")

Output:

35 min
Duration(15)
True
True
False

a + b uses the addition protocol; here it creates a new duration and leaves the inputs unchanged. print asks for the human-readable __str__; repr asks for the developer-oriented __repr__. Both return strings. Equality and less-than compare minutes, not object identity. The constructor assumes numeric minutes; this is a small model, not a complete time library.

NotImplemented is a special return value, not an exception: it lets Python try another applicable operation. If neither operand supports addition or ordering, Python normally raises TypeError; unsupported equality falls back, producing False in this example. Defining equality makes instances unhashable by default unless an appropriate hash is supplied. Defining __lt__ alone does not provide every ordering operation.

Other hooks include __sub__ for -, __mul__ for *, and __len__ for len. Give an operator a meaning callers can reasonably predict; a named method may communicate an unusual operation more clearly.

Chapter contents