Python 是否提供了一种访问最近封闭范围之外的变量的方法?

Does Python provide a way to access a variable beyond the nearest enclosing scope?

给出下面的例子,灵感来自 SO Question:

x = 0
def func1():
    x = 1
    def func2():
        x = 2
        def func3():
            KEYWORD x # scope declaration
            x = 3
        func3()
    func2()
func1()

With global and nonlocal as KEYWORD, For x the values respectively 0 and 2 instead of 3.

Python是否提供了一种机制,可以在func3()中为x使用func1()的范围?或者只能在此处访问 globalfunc2func3 范围?

不,您不能使用 nonlocal 指定特定范围。它将始终选择最近的包含命名变量的封闭范围。

由于 Python 使用词法作用域,进入这种情况的唯一方法是自己编写所有作用域的代码。 (例如,当你写 func3 时,你 知道 它嵌套在 func2 中,所以你知道 func2 范围内的所有变量。)只是在编写代码时不要在每个作用域中重复使用相同的名称,nonlocal 会做正确的事情。 (我们将首先忽略编写如此深层嵌套代码的问题。)

x_global = 0
def func1():
    x_first = 1
    def func2():
        x_second = 2
        def func3():
            nonlocal x_first # scope declaration
            x_first = 3
        func3()
    func2()
func1()

相比之下,我们假设 Python 使用了动态范围。

x = 9

def func1():
    nonlocal x
    x = 3

def func2():
    x = 1
    func1()
    print(x)

def func3():
    print(x)

func2()    # Prints 3
print(x)   # Prints 9; the global variable hasn't been changed
func1()
print(x)   # Prints 3; the global variable *has* changed.

func1修改的变量现在取决于调用func1的范围。

实际Python,上面的序列会打印

1
3
3

as func1总是修改全局变量,无论是从全局范围还是从func2的局部范围调用。