Comprehensive guide to Operator Overloading in Python

Question:

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)

Asked By: Casebash

||

Answers:

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'
Answered By: Gonzalo

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

Answered By: Olivier Verdier
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.