Part 4 · Section 04
Polymorphism and Special Methods
Why does len(x) work on a list, a string and a dictionary? Why can you write a + b for numbers, strings and lists alike? The answer is polymorphism through special methods: Python’s syntax and built-in functions don’t care what type an object is, they just call a method with a reserved double-underscore name. Define that method in your class and your objects join in, so they print nicely, add, compare, work as dictionary keys, behave in if statements and can even be called like functions.
In this section you’ll learn:
__repr__and__str__: the developer view and the user view of an object, and which built-ins use which- arithmetic operators (
__add__,__mul__,__matmul__, unary and in-place operators), the reflected versions like__radd__, and the difference between returningNotImplementedand raisingNotImplementedError - rich comparisons, how Python reflects them, and how
functools.total_orderingfills in the missing ones - the contract between
__eq__and__hash__, and why defining one affects the other - how Python decides the truth value of an object (
__bool__, then__len__) - making instances callable with
__call__, including decorator classes - the
__del__finalizer, and why it’s rarely the right tool __format__and the format specification that follows the:in an f-string