python 有没有办法在python中重载+=?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/728361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:45:17  来源:igfitidea点击:

Is there a way to overload += in python?

pythonoperator-overloading

提问by Josh Gibson

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

我知道__add__覆盖 plus的方法,但是当我使用它覆盖 += 时,我最终遇到了两个问题之一:

(1) if __add__mutates self, then

(1) 如果__add__自我变异,则

z = x + y

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

当我真的不希望 x 在那里发生变异时,将变异 x。

(2) if __add__returns a new object, then

(2) 如果__add__返回一个新对象,则

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 += xis executed.

将返回没有 w 的东西,因为 z 和 tmp 在z += x执行后指向不同的对象。

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

我可以制作某种.append()方法,但+=如果可能的话,我更愿意重载。

回答by mipadi

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

是的。只需覆盖对象的__iadd__方法,该方法采用与add. 您可以在此处找到更多信息。