Assignment statement value

你离开我真会死。 提交于 2019-12-06 17:17:29

问题


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


回答1:


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))



回答2:


Another fine example:

>>a,b,c  = b = 1,2,3
>>b
(1, 2, 3)



回答3:


a = b = c = 2
b = 3
print a,b,c
>>> 2 3 2


来源:https://stackoverflow.com/questions/7012742/assignment-statement-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!