list .__ iadd__和list .__ add__的不同行为 [英] Different behaviour for list.__iadd__ and list.__add__

查看:62
本文介绍了list .__ iadd__和list .__ add__的不同行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

>>> x = y = [1, 2, 3, 4]
>>> x += [4]
>>> x
[1, 2, 3, 4, 4]
>>> y
[1, 2, 3, 4, 4]

然后考虑一下:

>>> x = y = [1, 2, 3, 4]
>>> x = x + [4]
>>> x
[1, 2, 3, 4, 4]
>>> y
[1, 2, 3, 4]

这两个为什么有区别?

(是的,我尝试搜索此内容).

(And yes, I tried searching for this).

推荐答案

__iadd__更改列表,而__add__返回 new 列表,如所示.

__iadd__ mutates the list, whereas __add__ returns a new list, as demonstrated.

x += y的表达式首先尝试调用__iadd__,然后调用__add__,紧接着是赋值(有关细微的修改,请参见Sven的评论).由于list具有__iadd__,所以它做了一点点'o突变魔术.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆