Is there a way to overload += in python?

PythonOperator Overloading

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJosh GibsonView Question on Stackoverflow
Solution 1 - PythonmipadiView Answer on Stackoverflow