Python 的闭包——赋值前引用的局部变量

标签 python

我想了解闭包在 Python 中的工作原理。

我觉得 add1 在这里应该可以正常工作。我希望在调用 helper 时定义变量 x 。但是,它给我一个 Local variable referenced before assignment 错误。

add2add1 非常相似。它没有为 x 分配一个整数,而是为它分配了一个字典。它的行为也符合我的预期。 xhelper 中定义并可引用。

import random

def add1():
    x = 0
    def helper():
        x = x + 1
        return x
    return helper

def add2():
    x = {}
    def helper():
        x[random.randint(1,1000)] = 3
        return x
    return helper

if __name__ == '__main__':
    a1 = add1()
    a2 = add2()

    # print(a1()) #This causes error
    print(a2()) #{650: 3}
    print(a2()) #{650: 3, 333: 3}

这背后的逻辑是什么?除了 x 的类型不同之外,我在做什么?

最佳答案

您希望编译器知道该变量已绑定(bind)到闭包之外。这不是真的,因此您需要使用 nonlocal 来表明这一点。

def add1():
    x = 0
    def helper():
        nonlocal x
        x = x + 1
        return x
    return helper

丹尼斯编辑:

nonlocaladd2 中不是必需的,因为它只是修改 x 而不是重新绑定(bind)它(也不是重新分配它)。而在 add1 中,x= x+1 是一个重新赋值

关于Python 的闭包——赋值前引用的局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36901798/

相关文章:

python - 如何在 Python 中模拟 SendGrid 方法

python - 设置或更改新 xarray 维度的值

python - Flask-SQLAlchemy 连接

python - 在 wxPython 中动画 gif

python - 如何在 Python 中读取整个文件?在命令行中普遍工作

python - 键入 s 与键入不键入 s 速度

python - 如何在python中将unicode字符串转换为普通文本

python - 从 sklearn 导入时出现 ImportError : cannot import name check_build

Python - 如何找到两个向量之间的相关性?

python - 在子进程之前写出