python - list.__iadd__ 和 list.__add__ 的不同行为

标签 python list

考虑以下代码:

>>> 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]

为什么这两个有区别?

(是的,我试着搜索这个)。

最佳答案

__iadd__ 改变列表,而 __add__ 返回一个列表,如演示的那样。

x += y 的表达式首先尝试调用 __iadd__ ,如果失败,则在赋值后调用 __add__ (参见 Sven 的评论进行较小的更正)。因为 list__iadd__ 然后它做了一点点的变异魔法。

关于python - list.__iadd__ 和 list.__add__ 的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9766387/

相关文章:

python - Pandas:使用 groupby 计算添加标志

python - 如何向 tf.layers.Conv3D 提供输入层?

python:动态创建列表

java - 添加到列表抛出的前面?

python - 从 df 列连接列表

python - 无法在 macbook air 中创建 conda 环境(Resolvepackagenotfound)

python - Spyder/iPython 内联绘图图形大小

python - 按字母顺序对元组列表进行排序(区分大小写)

python - 批量更新 Python 列表的一部分

python - 我收到递归错误 [RuntimeError : maximum recursion depth exceeded while calling a Python object] - but my code is iterative -- or is it?