Hooking into the power of special methods

Methods with names that begin and end with two underscores—special methods—are also called hooks. They have special behaviors. When you use an operator such as +,

Python calls the special method_add_behind the scenes. If you implement the

_add_() method for your class, Python will call it each time you use the + operator with instances of your class.

Tip These methods are provided so you can make your own class instances work the same way Python's built-in types do. It's good practice not to change the behavior of the operators in ways users and readers of your program don't expect (such as changing_add_so that it subtracts!).

Table 13-1 lists some of the operator overloading methods. To see them in the documentation for most of Python's built-in data types, type help(data_type), substituting the name of the data type you need help with—for example, heip(iist).

Table 13-1: Some Commonly Used Special Methods ■=>Open table as spreadsheet


Used For


add ()


X + Y

eq (), neq () and others


x == y, x != y, and so on

getattr ()

Looking up


getitem ()

Retrieving an index or key

X[key], X[index], X in Y, used in loops and tests

init ()

Initializing objects


iter ()

Creates iterables

iter(X), for i in X:

repr ()

Printing, converting

print X, X

setattr ()

Assigning a value to an attribute

X.attr name = value

setitem ()

Assigning an index or key

X[key] = value X[index] = value


Converting objects to strings


For a complete list of special methods, see "Special method names" in the Python Language Reference: http://www.docs.python.org/ref/specialnames.html.

Was this article helpful?

0 0

Post a comment