Summary
We've looked at a number of basic special methods, which are essential features of any class that we design. These methods are already part of every class, but the defaults we inherit from the object may not match our processing requirements.
We'll almost always have a need to override __repr__()
, __str__()
, and __format__()
. The default implementations of these methods aren't very helpful at all.
We rarely need to override __bool__()
unless we're writing our own collection. That's the subject of Chapter 6, Creating Containers and Collections.
We often need to override the comparison and __hash__()
methods. The definitions are suitable for simple immutable objects but not at all appropriate for mutable objects. We may not need to write all the comparison operators; we'll look at the @functools.total_ordering
decorator in Chapter 8, Decorators and Mixins – Cross-cutting Aspects.
The other two basic special method names, __new__()
and __del__()
, are for more specialized purposes. Using...