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:

  1. >>> class MyList(object):
  2. ... def __init__(self, *a): self.a = list(a)
  3. ... def __len__(self): return len(self.a)
  4. ... def __getitem__(self, i): return self.a[i]
  5. ... def __setitem__(self, i, j): self.a[i] = j
  6. ...
  7. >>> b = MyList(3, 4, 5)
  8. >>> print b[1]
  9. 4
  10. >>> b.a[1] = 7
  11. >>> print b.a
  12. [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__.