赋值语句值 [英] Assignment statement value
问题描述
每个人都知道在 Python 中赋值不返回值,大概是为了避免在通常只是比较的情况下对 if
语句进行赋值:
出于同样的原因,人们可能会怀疑同一语句上的多个赋值也是语法错误.
事实上,a = (b = 2)
不是一个有效的表达式:
所以,我的问题是:为什么 a = b = 2
在 Python 中可以像在其他赋值语句具有值的语言(如 C)中一样工作?
这种行为有记录吗?我在赋值语句文档中找不到任何关于此的内容:http://docs.python.org/reference/simple_stmts.html#assignment-statements
就在语法中:
assignment_stmt ::= (target_list "=")+ (expression_list | yield_expression)
(target_list "=")+
末尾的小+
表示一个或多个".因此,a = b = c = 2
行不包含 3 个赋值语句,而是包含 一个带有 3 个目标列表的赋值语句.
每个目标列表依次只包含一个目标(在本例中为标识符).
它也在文本中(强调我的):
<块引用>赋值语句 [...] 将单个结果对象从左到右分配给每个目标列表.
这可能会导致有趣的结果:
<预><代码>>>>(a,b) = c = (1,2)>>>(a, b, c)(1, 2, (1, 2))Everybody knows that in Python assignments do not return a value, presumably to avoid assignments on if
statements when usually just a comparison is intended:
>>> if a = b:
File "<stdin>", line 1
if a = b:
^
SyntaxError: invalid syntax
>>> if a == b:
... pass
...
For the same reason, one could suspect that multiple assignments on the same statement were also syntax errors.
In fact, a = (b = 2)
is not a valid expression:
>>> a = (b = 2)
File "<stdin>", line 1
a = (b = 2)
^
SyntaxError: invalid syntax
So, my question is: why a = b = 2
works in Python as it works in other languages where assignment statements have a value, like C?
>>> a = b = c = 2
>>> a, b, c
(2, 2, 2)
Is this behavior documented? I could not found anything about this in the assignment statement documentation: http://docs.python.org/reference/simple_stmts.html#assignment-statements
It's right there in the syntax:
assignment_stmt ::= (target_list "=")+ (expression_list | yield_expression)
The tiny +
at the end of (target_list "=")+
means "one or more". So the line a = b = c = 2
does not consist of 3 assignment statements, but of a single assignment statement with 3 target lists.
Each target list in turn consist only of a single target (an identifier in this case).
It's also in the text (emphasis mine):
An assignment statement [...] assigns the single resulting object to each of the target lists, from left to right.
This can lead to interesting results:
>>> (a,b) = c = (1,2)
>>> (a, b, c)
(1, 2, (1, 2))
这篇关于赋值语句值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!