Special attributes, methods and operators
Class attributes, methods, and operators starting with a double underscore are usually intended to be private (i.e. to be used internally but not exposed outside the class) although this is a convention that is not enforced by the interpreter.
Some of them are reserved keywords and have a special meaning.
Here, as an example, are three of them:
__len__
__getitem__
__setitem__
They can be used, for example, to create a container object that acts like a list:
>>> class MyList(object):
... def __init__(self, *a): self.a = list(a)
... def __len__(self): return len(self.a)
... def __getitem__(self, i): return self.a[i]
... def __setitem__(self, i, j): self.a[i] = j
...
>>> b = MyList(3, 4, 5)
>>> print b[1]
4
>>> b.a[1] = 7
>>> print b.a
[3, 7, 5]
Other special operators include __getattr__
and __setattr__
, which define the get and set attributes for the class, and __sum__
and __sub__
, which overload arithmetic operators. For the use of these operators we refer the reader to more advanced books on this topic. We have already mentioned the special operators __str__
and __repr__
.