一行上的Python变量分配

时间:2019-10-27 06:53:16

标签: python

为什么这样做:

def make_fib():
    cur, next = 0, 1
    def fib():
        nonlocal cur, next
        result = cur
        cur, next = next, cur + next
        return result
    return fib

工作方式不同于:

def make_fib():
    cur, next = 0, 1
    def fib():
        nonlocal cur, next
        result = cur
        cur = next
        next = cur + next
        return result
    return fib

我看到第二个如何混乱,因为在cur = next和next = cur + next时,因为本质上它将变为next = next + next,但是为什么第一个运行方式不同?

1 个答案:

答案 0 :(得分:6)

cur, next = next, cur + next

与以下操作相同:

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

# assignment
cur = tmp_1
next = tmp_2

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

相关问题