您可以在 Python 中将加法赋值 ( += ) 运算符与海象运算符 ( := ) 结合使用吗?
Can you combine the addition assignment ( += ) operator with the walrus operator ( := ) in Python?
这是我现在写的代码:
a = 1
if (a := a + 1) == 2:
print(a)
我想知道是否存在这样的东西:
a = 1
if (a +:= 1) == 2:
print(a)
PEP-527 defined the new walrus operator. The section 讨论赋值语句和表达式之间的区别明确指出:
Augmented assignment is not supported:
total += tax # Equivalent: (total := total + tax)
在 section 解释为什么 =
仍然需要 :=
时,我们发现:
The two forms have different flexibilities. The := operator can be used inside a larger expression; the = statement can be augmented to += and its friends, can be chained, and can assign to attributes and subscripts.
这强烈暗示无意支持海象和任何类型的就地运算符的合并。
这是我现在写的代码:
a = 1
if (a := a + 1) == 2:
print(a)
我想知道是否存在这样的东西:
a = 1
if (a +:= 1) == 2:
print(a)
PEP-527 defined the new walrus operator. The section 讨论赋值语句和表达式之间的区别明确指出:
Augmented assignment is not supported:
total += tax # Equivalent: (total := total + tax)
在 section 解释为什么 =
仍然需要 :=
时,我们发现:
The two forms have different flexibilities. The := operator can be used inside a larger expression; the = statement can be augmented to += and its friends, can be chained, and can assign to attributes and subscripts.
这强烈暗示无意支持海象和任何类型的就地运算符的合并。