我需要找到x = "Nonlocal"
从引用变量的方法inner_function_nonlocal()
。可能是我参考x = "Global"
:的方式globals()['x']
,但是请您帮忙!
请注意:我不能发表评论或删除x = "Local"
以nonlocal x
代替它。
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句