Augmented assignment is the combination, in a single statement, of a binary operation and an assignment statement:
增量赋值就是在单条语句内合并一个二元运算和一个赋值语句。
augmented_assignment_stmt |
::= | target augop expression_list |
augop |
::= | "+=" | "-=" | "*=" | "/=" | "%=" | "**=" |
| "»=" | "«=" | "&=" | "^=" | "|=" |
(See section 5.3 for the syntax definitions for the last three symbols.)
(最后三项符号的语法定义见5.3节)
An augmented assignment evaluates the target (which, unlike normal assignment statements, cannot be an unpacking) and the expression list, performs the binary operation specific to the type of assignment on the two operands, and assigns the result to the original target. The target is only evaluated once.
一条增量赋值语句对目标(和一般的赋值语句不同,它不能是展开的对象)和表达式列表求值,执行特定于两个操作数的赋值类型的二元运算,并将结果赋值给原先的目标。目标仅求值一次。
An augmented assignment expression like x += 1
can be rewritten as
x = x + 1
to achieve a similar, but not exactly equal effect. In the
augmented version, x
is only evaluated once. Also, when possible, the
actual operation is performed in-place, meaning that rather than
creating a new object and assigning that to the target, the old object is
modified instead.
一条赋值语句,比如 x+= 1, 可以重写为 x = x + 1, 效果是类似的,但并不完全一样。在增量版本中,x仅求值一次。而且,只要可能,实际的操作是就地进行的,意思是并非创建一个新对象然后将其赋值给目标,而是修改老的对象。
With the exception of assigning to tuples and multiple targets in a single statement, the assignment done by augmented assignment statements is handled the same way as normal assignments. Similarly, with the exception of the possible in-place behavior, the binary operation performed by augmented assignment is the same as the normal binary operations.
除了在一条语句中赋值给元组和多个对象的情况,增量赋值语句所完成的赋值用与普通赋值同样的方式处理。类似地,除了可能的就地方式,由增量赋值执行的二元运算和普通的二元运算也是一样的。
For targets which are attribute references, the initial value is retrieved with a getattr() and the result is assigned with a setattr(). Notice that the two methods do not necessarily refer to the same variable. When getattr() refers to a class variable, setattr() still writes to an instance variable. For example:
class A: x = 3 # class variable a = A() a.x += 1 # writes a.x as 4 leaving A.x as 3