Special Methods
A
class may define or inherit special methods (i.e., methods whose
names begin and end with double underscores). Each special method
relates to a specific operation. Python implicitly invokes a special
method whenever you perform the related operation on an instance
object. In most cases, the method’s return value is
the operation’s result, and attempting an operation
when its related method is not present raises an exception.
Throughout this section, I will point out the cases in which these
general rules do not apply. In the following,
x is the instance of class
C on which you perform the operation, and
y is the other operand, if any. The formal
argument self of each method also refers to
instance object
x.
General-Purpose Special Methods
Some special methods relate to general-purpose operations. A class that defines or inherits these methods allows its instances to control such operations. These operations can be divided into the following categories:
- Initialization and finalization
An instance can control its initialization (a frequent need) via special method
__init__, and/or its finalization (a rare need) via__del__.- Representation as string
An instance can control how Python represents it as a string via special methods
__repr__,__str__, and__unicode__.- Comparison, hashing, and use in a Boolean context
An instance can control how it compares with other objects (methods
__lt__and__cmp__), how dictionaries use it as a key (__hash__), and whether it evaluates ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access