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. Whenever, in the following sections, I mention calls to x._ _name_ _(...), keep in mind that, for new-style classes, the exact call happening is rather, pedantically speaking, x._ _class_ _._ _name_ _(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

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

Representation as string

A class can control how Python represents its instances as strings ...

Get Python in a Nutshell, 2nd Edition 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.