引用某事:
>>> x = y = somefunction()
是相同的
>>> y = somefunction()
>>> x = y
问题: 是
x = y = somefunction()
与
x = somefunction()
y = somefunction()
?
根据我的理解,它们应该是相同的,因为somefunction
只能返回一个值。
左先
x = y = some_function()
相当于
temp = some_function()
x = temp
y = temp
注意顺序。最左边的目标首先被分配。 (C 中类似的表达式may https://stackoverflow.com/a/19356014/673991分配在相反的顺序 https://stackoverflow.com/a/24641021/673991.) 从文档开始Python作业 https://docs.python.org/reference/simple_stmts.html#assignment-statements:
...将单个结果对象从左到右分配给每个目标列表。
反汇编显示:
>>> def chained_assignment():
... x = y = some_function()
...
>>> import dis
>>> dis.dis(chained_assignment)
2 0 LOAD_GLOBAL 0 (some_function)
3 CALL_FUNCTION 0
6 DUP_TOP
7 STORE_FAST 0 (x)
10 STORE_FAST 1 (y)
13 LOAD_CONST 0 (None)
16 RETURN_VALUE
注意:同一个物体 http://www.diveintopython.net/getting_to_know_python/everything_is_an_object.html始终分配给每个目标。因此,正如 @Wilduck 和 @andronikus 指出的那样,你可能永远不会想要这个:
x = y = [] # Wrong.
在上面的例子中,x 和 y 指的是同一个列表。因为列表是mutable https://en.wikibooks.org/wiki/Python_Programming/Data_Types#Mutable_vs_Immutable_Objects,附加到 x 将似乎影响 http://bjc.berkeley.edu/bjc-r/cur/programming/python/list_mutability.html y.
x = [] # Right.
y = []
现在您有两个名称引用两个不同的空列表。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)