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 ...

Get Python in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.