The global statement can be used to indicate that particular variables live in the global scope and should be rebound there; the nonlocal statement indicates that particular variables live in an enclosing scope and should be rebound there.
还是看python代码来理解吧,这是官方的示例,注释是麦新杰加的:
def scope_test():
def do_local():
spam = "local spam" #do_local()函数本地的变量,谁都不影响
def do_nonlocal():
nonlocal spam
spam = "nonlocal spam" #申明这个spam变量是来自外层namespace
def do_global():
global spam
spam = "global spam" #申明这个spam变量来自全局namespace,注意,这个全局变量在此之前还不存在
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)
这段代码运行的结果如下:
After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam # 代码执行到这里,实际上是申明了一个全局变量并给它赋值。
In global scope: global spam
这样,我们就理解了python的global和nonlocal申明的含义。