Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to overload += in python? [duplicate]

I know about the __add__ method to override plus, but when I use that to override +=, I end up with one of two problems:

(1) if __add__ mutates self, then

z = x + y 

will mutate x when I don't really want x to be mutated there.

(2) if __add__ returns a new object, then

tmp = z z += x z += y tmp += w return z 

will return something without w since z and tmp point to different objects after z += x is executed.

I can make some sort of .append() method, but I'd prefer to overload += if it is possible.

like image 454
Josh Gibson Avatar asked Apr 08 '09 03:04

Josh Gibson


People also ask

Is overloading possible in Python?

Python supports both function and operator overloading. In function overloading, we can use the same name for many Python functions but with the different number or types of parameters. With operator overloading, we are able to change the meaning of a Python operator within the scope of a class.

Can you overload print in Python?

Overloading print is a design feature of python 3.0 to address your lack of ability to do so in python 2. x. However, you can override sys. stdout.

Which function overloads == in Python?

Python does not support function overloading. When we define multiple functions with the same name, the later one always overrides the prior and thus, in the namespace, there will always be a single entry against each function name.

Is overloading and overriding possible in Python?

Note: Python does not support method overloading. We may overload the methods but can only use the latest defined method.


1 Answers

Yes. Just override the object's __iadd__ method, which takes the same parameters as add. You can find more information here.

like image 193
mipadi Avatar answered Sep 22 '22 21:09

mipadi