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)
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'
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)
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)
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'
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)