+ and += operators are different?
1 2 3 4 5 6 7 8 9 10 11 12 13 | >>> 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 |
有什么区别?+=和+不应该仅仅是句法上的糖分吗?
医生解释得很好,我想:
__iadd__() , etc.
These methods are called to implement the augmented arithmetic assignments (+=, -=, *=, /=, //=, %=, **=, <<=, >>=, &=, ^=, |= ). These methods should attempt to do the operation in-place (modifyingself ) 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 statementx += y , wherex is an instance of a class that has an__iadd__() method,x.__iadd__(y) is called.
另外,您会注意到,
1 2 3 4 5 6 | >>> c = 3 >>> print(c, id(c)) 3 505389080 >>> c += c >>> print(c, id(c)) 6 505389128 |
它们不一样
C+=C将C内容的副本附加到C本身
C=C+C用C+C创建新对象
为了
1 | foo = [] |
在第一种情况下,您只是将列表的成员添加到另一个列表中(而不是创建新的列表)。
在第二种情况下,
如果你用不同的列表(而不是C本身)重新表述这个问题,它可能会变得更清晰。
+=运算符将第二个列表附加到第一个列表,但修改已就位,因此ID保持不变。
当您使用+时,会创建一个新列表,最后一个"c"是一个新列表,因此它具有不同的ID。
但两个操作的最终结果是相同的。