+和+ =运算符是否不同? [英] + and += operators are different?
问题描述
>>> 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
有什么区别? + =和+不应该仅仅是语法糖吗?
What's the difference? are += and + not supposed to be merely syntactic sugar?
推荐答案
文档解释很好,我认为:
__iadd__()
等
调用这些方法以实现增强的算术分配(+=, -=, *=, /=, //=, %=, **=, <<=, >>=, &=, ^=, |=
). 这些方法应尝试就地进行操作(修改self
)并返回结果(可以但不一定是self
).如果未定义,则扩充后的分配将回退到常规方法.例如,要执行语句x += y
,其中x
是具有__iadd__()
方法的类的实例,则调用x.__iadd__(y)
.
__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.
+=
旨在实现就地修改.在简单添加的情况下,将创建新对象,并使用已使用的名称(c
)对其进行标记.
+=
are designed to implement in-place modification. in case of simple addition, new object created and it's labelled using already-used name (c
).
此外,您还会注意到,由于列表的可变性,+=
运算符的这种行为仅可能发生.整数-一种不可变的类型-不会产生相同的结果:
Also, you'd notice that such behaviour of +=
operator only possible because of mutable nature of lists. Integers - an immutable type - won't produce the same result:
>>> c = 3
>>> print(c, id(c))
3 505389080
>>> c += c
>>> print(c, id(c))
6 505389128
这篇关于+和+ =运算符是否不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!