list .__ iadd__和list .__ add__的不同行为

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.