我有一个局部变量x = "local"
,很不幸,它与全局变量和非局部变量都共享其名称。在不更改任何名称的情况下,我可以访问所有三个值吗?对于x = "global"
,有globals()
,但是非局部变量呢?
说明问题的最小示例:
x = "global"
def f(x="nonlocal"):
def g():
x = "local"
print(x) # same as locals()["x"]
print(globals()["x"])
# here I want to print the non-local x
return g
f()()
我没有得到您的上下文,您必须使用相同的名称。无论如何,您都可以将外部函数的局部变量捕获为非局部变量。
x = "global"
def f(x="nonlocal"):
nonlocals = locals()
def g():
x = "local"
print(x)
print(nonlocals['x'])
print(globals()["x"])
return g
f()()
输出:
local
nonlocal
global
我质疑其背后的原理,但是在Python 3中,您可以使用nonlocal
关键字来访问先前的作用域,在重新声明之前存储该作用域,然后再获取它。
x = "global"
def f(x="nonlocal"):
def g():
nonlocal x
y = x
x = "local"
print(x) # same as locals()["x"]
print(globals()["x"])
print(y)
return g
f()()
输出
local
global
nonlocal