list.__iadd__ 和 list.__add__ 的不同行为 [英] Different behaviour for list.__iadd__ and list.__add__
本文介绍了list.__iadd__ 和 list.__add__ 的不同行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑以下代码:
<预><代码>>>>x = y = [1, 2, 3, 4]>>>x += [4]>>>X[1, 2, 3, 4, 4]>>>是[1, 2, 3, 4, 4]然后考虑这个:
<预><代码>>>>x = y = [1, 2, 3, 4]>>>x = x + [4]>>>X[1, 2, 3, 4, 4]>>>是[1, 2, 3, 4]为什么这两者有区别?
(是的,我试过搜索这个).
解决方案
__iadd__
改变列表,而 __add__
返回一个 new 列表,如演示.
x += y
的表达式首先尝试调用 __iadd__
,如果失败,则调用 __add__
跟随一个赋值(见 Sven 的评论进行小幅修正).由于 list
有 __iadd__
那么它就做了一点o 变异魔法".
consider the following code:
>>> x = y = [1, 2, 3, 4]
>>> x += [4]
>>> x
[1, 2, 3, 4, 4]
>>> y
[1, 2, 3, 4, 4]
and then consider this:
>>> x = y = [1, 2, 3, 4]
>>> x = x + [4]
>>> x
[1, 2, 3, 4, 4]
>>> y
[1, 2, 3, 4]
Why is there a difference these two?
(And yes, I tried searching for this).
解决方案
__iadd__
mutates the list, whereas __add__
returns a new list, as demonstrated.
An expression of x += y
first tries to call __iadd__
and, failing that, calls __add__
followed an assignment (see Sven's comment for a minor correction). Since list
has __iadd__
then it does this little bit 'o mutation magic.
这篇关于list.__iadd__ 和 list.__add__ 的不同行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文