nonlocal语句
nonlocal语句和global是近亲。它和global的不同之处在于,nonlocal应用于一个嵌套的函数的作用域中修改名称,而不是所有def之外的全局模块作用域;而且在声明nonlocal名称的时候,它必须已经存在于该嵌套函数的作用域中——它们可能只存在于嵌套的函数中,并且不能由一个嵌套的def中的第一次赋值创建。
nonlocal应用
我们先来看一些nonlocal的例子
#示例1
>>> def tester(start):
... state = start
... def nested(label):
... print(label,state)
... return nested
...
>>> F = tester(0)
>>> F('spam')
spam 0
#尝试在嵌套的def内修改state
>>> def tester(start):
... state = start
... def nested(label):
... print(label,state)
... state += 1
... return nested
...
>>> F = tester(0)
>>> F('spam')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in nested
UnboundLocalError: local variable 'state' referenced before assignment
使用nonlocal进行修改后:
#示例2
>>> def tester(start):
... state = start
... def nested(label):
... nonlocal state
... print(label,state)
... state += 1
... return nested
...
>>> F = tester(0)
>>> F('spam')
spam 0
>>> F('ham')
ham 1
>>> F('YAMAHA')
YAMAHA 2
>>> G = tester(45)
>>> G('China')
China 45
>>> F('re')
re 3
注意:
- nonlocal语句允许在内存中保存可变状态的副本,并且解决了在类无法保证的情况下简单的状态保存。(在示例2中有这样的体现)
- 当执行一条nonlocal语句时,nonlocal名称必须已经在一个嵌套的def作用域中赋值过,否则将会得到一个错误——不能通过在嵌套的作用域给它们一个新值来创建它们(即边界情况)