在浏览Python Scope文档时,我遇到了以下代码,但我不确定此代码的执行是如何工作的。有人可以解释这段代码吗?
def scope_test():
def do_local():
spam = "local spam"
def do_nonlocal():
nonlocal spam
spam = "nonlocal spam"
def do_global():
global spam
spam = "global spam"
spam = "test spam"
do_local()
print("After local assignment:", spam)
do_nonlocal()
print("After nonlocal assignment:", spam)
do_global()
print("After global assignment:", spam)
scope_test()
print("In global scope:", spam)
答案 0 :(得分:0)
最简单的方法 - 运行程序! 这是输出:
After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam
如您所见,nonlocal在定义的范围内具有优先权。一旦出局,就使用全局定义。无需重置全局值,这是自动完成的。当然,非本地覆盖本地分配。
修改:有关详细信息,请参阅this related question。