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)
Operator Overloading means giving extended meaning beyond their predefined operational meaning. For example operator + is used to add two integers as well as join two strings and merge two lists. It is achievable because '+' operator is overloaded by int class and str class.
The operator overloading in Python means provide extended meaning beyond their predefined operational meaning. Such as, we use the "+" operator for adding two integers as well as joining two strings or merging two lists. We can achieve this as the "+" operator is overloaded by the "int" class and "str" class.
A very popular and convenient example is the Addition (+) operator. Just think how the '+' operator operates on two numbers and the same operator operates on two strings. It performs “Addition” on numbers whereas it performs “Concatenation” on strings.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With