一行上的Python变量分配

gym*_*y42 0 python

为什么这样做:

def make_fib():
    cur, next = 0, 1
    def fib():
        nonlocal cur, next
        result = cur
        cur, next = next, cur + next
        return result
    return fib
Run Code Online (Sandbox Code Playgroud)

工作方式不同于:

def make_fib():
    cur, next = 0, 1
    def fib():
        nonlocal cur, next
        result = cur
        cur = next
        next = cur + next
        return result
    return fib
Run Code Online (Sandbox Code Playgroud)

我看到第二个怎么弄乱了,因为在cur = next和next = cur + next时,因为本质上它将变成next = next + next,但是第一个为什么运行不同?

njz*_*zk2 6

cur, next = next, cur + next
Run Code Online (Sandbox Code Playgroud)

与以下操作相同:

# right-hand side operations
tmp_1 = next
tmp_2 = cur + next

# assignment
cur = tmp_1
next = tmp_2
Run Code Online (Sandbox Code Playgroud)

因为对右侧进行了充分评估,然后将值分配给左侧