33
votes

Is there a comprehensive guide to operator overloading anywhere? Preferably online, but a book would be fine too. The description of the operator module leaves a lot out, such as including operators that can't be overloaded and missing the r operators or providing sensible defaults. (Writing these operators is good practice, but still belongs in a good reference)

2
The document you are looking for is here in Python documentation - Antti Haapala

2 Answers

25
votes

I like this reference to quickly see which operators may be overloaded:

http://rgruet.free.fr/PQR26/PQR2.6.html#SpecialMethods

Here is another resource, for completeness (and also for Python 3)

http://www.python-course.eu/python3_magic_methods.php

49
votes

Python's operator overloading is done by redefining certain special methods in any class. This is explained in the Python language reference.

For example, to overload the addition operator:

>>> class MyClass(object):
...     def __add__(self, x):
...         return '%s plus %s' % (self, x)
... 
>>> obj = MyClass()
>>> obj + 1
'<__main__.MyClass object at 0xb77eff2c> plus 1'

The relevant section in the Python 3 documentation can be seen here.