python – 和=运算符是不同的?

参见英文答案 > Why does += behave unexpectedly on lists?                                    7个

>>> c = [1, 2, 3]
>>> print(c, id(c))
[1, 2, 3] 43955984
>>> c += c
>>> print(c, id(c))
[1, 2, 3, 1, 2, 3] 43955984
>>> del c
>>> c = [1, 2, 3]
>>> print(c, id(c))
[1, 2, 3] 44023976
>>> c = c + c
>>> print(c, id(c))
[1, 2, 3, 1, 2, 3] 26564048

有什么不同?是=并不应该仅仅是语法糖?

最佳答案
docs explain it very well,我想:

__iadd__(), etc.
These methods are called to implement the augmented arithmetic assignments (+=, -=, *=, /=, //=, %=, **=, <<=, >>=, &=, ^=, |=). These methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self). If a specific method is not defined, the augmented assignment falls back to the normal methods. For instance, to execute the statement x += y, where x is an instance of a class that has an __iadd__() method, x.__iadd__(y) is called.

 =旨在实现就地修改.在简单添加的情况下,创建新对象并使用已使用的名称(c)进行标记.

此外,您会注意到=运算符的这种行为只能由于列表的可变性而可能.整数 – 不可变类型 – 不会产生相同的结果:

>>> c = 3
>>> print(c, id(c))
3 505389080
>>> c += c
>>> print(c, id(c))
6 505389128

转载注明原文:python – 和=运算符是不同的? - 代码日志