【问题标题】:Why is nonlocal keyword being 'interrupted' by a global keyword?为什么非本地关键字被全局关键字“打断”?
【发布时间】:2019-09-03 00:34:05
【问题描述】:

我是一名尝试学习 python 的初学者程序员,我遇到了作用域这个话题。在执行最底层的代码时,我遇到了错误“没有找到非本地 var_name 的绑定”。有人能解释一下为什么 nonlocal 关键字无法“查看”中间函数并进入外部函数吗?


#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()

【问题讨论】:

    标签: python scope


    【解决方案1】:

    涉及nonlocal 关键字的表达式将导致Python 尝试在封闭的局部范围内查找变量,直到它第一次遇到第一个指定的变量name

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

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

    如果要确定变量globe 是否在某个函数的局部范围内,可以使用dir() 函数,因为来自Python docs

    不带参数,返回当前本地的名称列表 范围。使用参数,尝试返回有效属性列表 为那个对象。

    【讨论】:

    • 虽然公平地说 nonlocal 文档 (docs.python.org/3/reference/simple_stmts.html#nonlocal) 提到了 The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals.,所以根据它应该忽略全局变量,但它们似乎没有。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-17
    相关资源
    最近更新 更多