如果内部函数已经有同名Python的变量,如何从内部函数访问封闭函数中的非局部变量



我需要找到从inner_function_nonlocal()引用变量x = "Nonlocal"的方法。可能是我引用x = "Global":globals()['x']的方式,但我需要你的帮助!

请注意:我不能为了写nonlocal x而评论或删除x = "Local"

x = "Global"

def enclosing_funcion():
x = "Nonlocal"
def inner_function_global():
x = "Local"
print(globals()['x'])   # Call the global a
def inner_function_nonlocal():
x = "Local"        # <- This line can NOT be commented!!!
print(_?_?_?_?_)   # <- What should I specify here in order to print x which is nonlocal?
inner_function_global()
inner_function_nonlocal()

if __name__ == '__main__':
enclosing_funcion()

输出应该是:

Global (this is already achieved)
Nonlocal (need help to get this one)

您可以添加一个方法来获取Nonlocal值:

x = "Global"
def enclosing_funcion():
x = "Nonlocal"
def non_local():
return x
def inner_function_global():
x = "Local"
print(globals()['x'])   # Call the global a
def inner_function_nonlocal():
x = "Local"        # <- This line can NOT be commented!!!
print(non_local())   # <- What should I specify here in order to print x which is nonlocal?
inner_function_global()
inner_function_nonlocal()

if __name__ == '__main__':
enclosing_funcion()

结果:

Global
Nonlocal

最新更新