+和+ =运算符是否不同? [英] + and += operators are different?

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

问题描述

>>> 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 (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)对其进行标记.

+= 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屋!

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