tags:

views:

76

answers:

2

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  A: 

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'
Gonzalo
+1 for the official reference!
EOL
+1  A: 

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

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

Olivier