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
Is there a way to overload += in python?
提问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 += x
is 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()
方法,但+=
如果可能的话,我更愿意重载。