为什么非本地关键字被全局关键字“打断”?

2024-04-26 14:07:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个试图学习python的初学者程序员,我遇到了范围这个话题。在执行最底层的代码时,我遇到了错误“找不到非本地var_name的绑定”。有人能解释为什么非局部关键字不能“查看”中间函数和外部函数吗


#this works
globe = 5


def outer():
    globe = 10
    def intermediate():

        def inner():
            nonlocal globe
            globe = 20
            print(globe)
        inner()
        print(globe)
    intermediate()
    print(globe)


outer()

globe = 5


def outer():
    globe = 10
    def intermediate():
        global globe #but not when I do this
        globe = 15
        def inner():
            nonlocal globe #I want this globe to reference 10, the value in outer()
            globe = 20
            print(globe)
        inner()
        print(globe)
    intermediate()
    print(globe)


outer()

Tags: 函数代码def错误this程序员innerprint
1条回答
网友
1楼 · 发布于 2024-04-26 14:07:18

包含nonlocal关键字的表达式将导致Python尝试在封闭的局部作用域中查找变量,直到它第一次遇到第一个指定的变量name

nonlocal globe表达式将查看intermediate函数中是否有名为globe的变量。但是,它将在global范围内遇到它,因此它将假定它已到达模块范围并完成对它的搜索,而没有找到nonclocal范围,因此出现异常

通过在intermediate函数中声明global globe,您基本上关闭了到达前面作用域中具有相同名称的任何nonlocal变量的路径。您可以看看讨论here为什么“决定”用Python以这种方式实现

如果要确保变量globe在或不在某个函数的局部范围内,可以使用dir()函数,因为从Python docs

Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.

相关问题 更多 >