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. Whenever, in the following sections, I mention calls to
(...), keep in mind that, for new-style classes, the exact call happening is rather, pedantically speaking,
._ _class_ _.
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:
A class can control its instances’ initialization (a frequent need) via special methods
_ _new_ _ (new-style classes only) and
_ _init_ _, and/or their finalization (a rare need) via
_ _del_ _.
A class can control how Python represents its instances as strings ...