Python赋值运算符不同于非赋值运算符 [英] Python assignment operator differs from non assignment
问题描述
我面临着这种奇怪的行为,我找不到任何解释.
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不会引发错误并将键附加到列表中,而当我仅计算 +
时,我得到了预期的TypeError
.
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)
,并在 l
为可变
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->TypeError
.
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 __(自身,其他)
l + {'B': 3}
TypeError: can only concatenate list (not "dict") to list
这篇关于Python赋值运算符不同于非赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!