Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

operator overloading in python [duplicate]

Possible Duplicates:
Python: defining my own operators?
Rules of thumb for when to use operator overloading in python

Is it possible to overload operators in Python? If so, can one define new operators, such as ++ and <<?

like image 576
Ahmad Dwaik Avatar asked Dec 20 '09 15:12

Ahmad Dwaik


People also ask

What is __ add __ in Python?

__add__ magic method is used to add the attributes of the class instance. For example, let's say object1 is an instance of a class A and object2 is an instance of class B and both of these classes have an attribute called 'a', that holds an integer.

Can we overload operator twice?

No this is not possible. The compiler can't know which version you want, it deducts it from the parameters. You can overload many times, but not by the return type.

What is operator overloading in Python with example?

For example, the + operator will perform arithmetic addition on two numbers, merge two lists, or concatenate two strings. This feature in Python that allows the same operator to have different meaning according to the context is called operator overloading.


2 Answers

As other answers have mentioned, you can indeed overload operators (by definining special methods in the class you're writing, i.e., methods whose names start and end with two underscores). All the details are here.

To complete the answers to you questions: you cannot define new operators; but << is not a new operator, it's an existing one, and it's overloaded by defining in the class the method __lshift__.

As a historical note, this is also pretty much the situation in C++ -- but the exact set of operators you can overload differs between the two languages. For example, in C++, you cannot overload attribute access, .; in Python, you can, with __getattr__ (or __getattribute__, with different semantics) and __setattr__. Vice versa, in Python = (plain assignment) is not an operator, so you cannot overload that, while in C++ it is an operator and you can overload it.

<< is an operator, and can be overloaded, in both languages -- that's how << and >>, while not losing their initial connotation of left and right shifts, also became I/O formatting operators in C++ (not in Python!-).

like image 132
Alex Martelli Avatar answered Sep 18 '22 15:09

Alex Martelli


See: http://docs.python.org/reference/datamodel.html#special-method-names.

A class can implement certain operations that are invoked by special syntax (such as arithmetic operations or subscripting and slicing) by defining methods with special names. This is Python’s approach to operator overloading, allowing classes to define their own behavior with respect to language operators.

like image 30
miku Avatar answered Sep 20 '22 15:09

miku