Python赋值运算符与非赋值不同 [英] Python assignment operator differs from non assignment

查看:45
本文介绍了Python赋值运算符与非赋值不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到过这种奇怪的行为,我找不到解释.

I have face this weird behavior I can not find explications about.

MWE:

l = [1]
l += {'a': 2}
l
[1, 'a']
l + {'B': 3}
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: can only concatenate list (not "dict") to list

基本上,当我 += python 不会引发错误并将键附加到列表时,而当我只计算 + 我得到预期的 类型错误.

Basically, when I += python does not raise an error and append the key to the list while when I only compute the + I get the expected TypeError.

注意:这是 Python 3.6.10

Note: this is Python 3.6.10

推荐答案

l += ... 实际上是在调用 object.__iadd__(self, other) 并在 lmutable

l += ... is actually calling object.__iadd__(self, other) and modifies the object in-place when l is mutable

原因(正如@DeepSpace 在他的评论中所解释的)是,当您执行 l += {'a': 2} 操作时,该操作只会在适当的位置更新 l并且仅当 l 是可变的.另一方面,操作 l + {'a': 2} 没有完成,导致 list + dictionary ->类型错误.

The reason (as @DeepSpace explains in his comment) is that when you do l += {'a': 2} the operation updates l in place only and only if l is mutable. On the other hand, the operation l + {'a': 2} is not done in place resulting into list + dictionary -> TypeError.

(参见此处)

l = [1]
l = l.__iadd__({'a': 2})
l
#[1, 'a']

与调用object.__add__(self, other)

l + {'B': 3}

TypeError: can only concatenate list (not "dict") to list

这篇关于Python赋值运算符与非赋值不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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