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 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.
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.
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.
Note: Python does not support method overloading. We may overload the methods but can only use the latest defined method.
Yes. Just override the object's __iadd__
method, which takes the same parameters as add
. You can find more information here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With