输出背后的原因是什么?

Kau*_*hik 1 python-3.x output

输入

x, y = 20, 60
y, x, y = x, y-10, x+10
print(x, y)
Run Code Online (Sandbox Code Playgroud)

输出

50 30
Run Code Online (Sandbox Code Playgroud)

我期望什么?

  • x = 20

  • y = 60

  • y = x = 20

  • x = y-10 = 20-10 = 10

  • y = x + 10 = 20

预期产量

10 20
Run Code Online (Sandbox Code Playgroud)

为什么不是这种情况?是因为首先对表达式求值,然后才给变量赋值?

Err*_*rse 7

右侧在左侧之前完全撤离。然后从左到右评估左侧。

x, y = 20, 60
# x = 20, y = 60

# ----------------------

y, x, y = x, y-10, x+10
# Evaulate the right first:
# x, y-10, x+10 = 20, 50, 30
# So now we have
# y, x, y = 20, 50, 30

# Now it goes left to right so:
# y = 20
# x = 50
# y = 30 --> note this overwrote the first y assignment

print(x, y)
Run Code Online (Sandbox Code Playgroud)

从而

50 30
Run Code Online (Sandbox Code Playgroud)