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