我有一个局部变量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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句