下面的示例受到 SO Question 中另一个示例的启发:
x = 0
def func1():
x = 1
def func2():
x = 2
def func3():
KEYWORD x # scope declaration
x = 3
func3()
func2()
func1()
以global
和nonlocal
为关键字,对于x
,值分别为0
和2
而不是 3
。
Python 是否提供了一种机制来将 func1()
的范围用于 func3()
中的 x
?或者这里只能访问 global
、func2
和 func3
作用域?
最佳答案
不,您不能使用 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
的局部作用域调用。
关于python - Python 是否提供了一种访问最近封闭范围之外的变量的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68761834/