I know about the __add__ method to override plus, but when I use that to override +=, I end up with one of two problems:
-
if
__add__mutates self, thenz = x + ywill mutate x when I don’t really want x to be mutated there.
-
if
__add__returns a new object, thentmp = z z += x z += y tmp += w return zwill return something without w since z and tmp point to different objects after
z += xis executed.
I can make some sort of .append() method, but I’d prefer to overload += if it is possible.
Yes. Just override the object’s
__iadd__method, which takes the same parameters asadd. You can find more information here.