Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comprehensive guide to Operator Overloading in Python [closed]

Tags:

python

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)

like image 781
Casebash Avatar asked Mar 08 '10 10:03

Casebash


People also ask

What is operator overloading in Python explain it with example?

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.

How operator overloading can be implemented in Python?

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.

What is the most popular form of operator overloading in Python?

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.


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

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

like image 158
Gonzalo Avatar answered Oct 05 '22 13:10

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

like image 35
Olivier Verdier Avatar answered Oct 05 '22 13:10

Olivier Verdier