Learning Python - Mark Lutz [388]
__call__
Function calls
X(*args, **kargs)
__getattr__
Attribute fetch
X.undefined
__setattr__
Attribute assignment
X.any = value
__delattr__
Attribute deletion
del X.any
__getattribute__
Attribute fetch
X.any
__getitem__
Indexing, slicing, iteration
X[key], X[i:j], for loops and other iterations if no __iter__
__setitem__
Index and slice assignment
X[key] = value, X[i:j] = sequence
__delitem__
Index and slice deletion
del X[key], del X[i:j]
__len__
Length
len(X), truth tests if no __bool__
__bool__
Boolean tests
bool(X), truth tests (named __nonzero__ in 2.6)
__lt__, __gt__, __le__, __ge__, __eq__, __ne__
Comparisons
X < Y, X > Y, X <= Y, X >= Y, X == Y, X != Y (or else __cmp__ in 2.6 only)
__radd__
Right-side operators
Other + X
__iadd__
In-place augmented operators
X += Y (or else __add__)
__iter__, __next__
Iteration contexts
I=iter(X), next(I); for loops, in if no __contains__, all comprehensions, map(F,X), others (__next__ is named next in 2.6)
__contains__
Membership test
item in X (any iterable)
__index__
Integer value
hex(X), bin(X), oct(X), O[X], O[X:] (replaces Python 2 __oct__, __hex__)
__enter__, __exit__
Context manager (Chapter 33)
with obj as var:
__get__, __set__, __delete__
Descriptor attributes (Chapter 37)
X.attr, X.attr = value, del X.attr
__new__
Creation (Chapter 39)
Object creation, before __init__
All overloading methods have names that start and end with two underscores to keep them distinct from other names you define in your classes. The mappings from special method names to expressions or operations are predefined by the Python language (and documented in the standard language manual). For example, the name __add__ always maps to + expressions by Python language definition, regardless of what an __add__ method’s code actually does.
Operator overloading methods may be inherited from superclasses if not defined, just like any other methods. Operator overloading methods are also all optional—if you don’t code or inherit one, that operation is simply unsupported by your class, and attempting it will raise an exception. Some built-in operations, like printing, have defaults (inherited for the implied object class in Python 3.0), but most built-ins fail for class instances if no corresponding operator overloading method is present.
Most overloading methods are used only in advanced programs that require objects to behave like built-ins; the __init__ constructor tends to appear in most classes, however, so pay special attention to it. We’ve already met the __init__ initialization-time constructor method, and a few of the others in Table 29-1. Let’s explore some of the additional methods in the table by example.
Indexing and Slicing: __getitem__ and __setitem__
If defined in a class (or inherited by it), the __getitem__ method is called automatically for instance-indexing operations. When an instance X appears in an indexing expression like X[i], Python calls the __getitem__ method inherited by the instance, passing X to the first argument and the index in brackets to the second argument. For example, the following class returns the square of an index value:
>>> class Indexer:
... def __getitem__(self, index):
... return index ** 2
...
>>> X = Indexer()
>>> X[2] # X[i] calls X.__getitem__(i)
4
>>> for i in range(5):
... print(X[i], end=' ') # Runs __getitem__(X, i) each time
...
0 1 4 9 16
Intercepting Slices
Interestingly, in addition to indexing, __getitem__ is also called for slice expressions. Formally speaking, built-in types handle slicing the same way. Here, for example, is slicing at work on a built-in list, using upper and lower bounds and a stride (see Chapter 7 if you need a refresher on slicing):
>>> L = [5, 6, 7, 8, 9]
>>> L[2:4] # Slice with slice syntax
[7, 8]
>>> L[1:]
[6, 7, 8, 9]
>>> L[:-1]
[5, 6, 7, 8]
>>> L[::2]