在看python学习手册,感觉实在痛苦,不知道外国佬说话就这范,还是中国人一翻译就成了这样. 不好好说话, 看了一晚上都不明白, 第二天问了师父后终于明白了.
nonlocal:简单的说就是使用母嵌套的变量. 多简单的一句话,让他说了3,4页.
def tester(start):
state = start
def nested(label):
###nonlocal state
print(label,state)
state += 1
return nested
F = tester(0)
F('spam')
F('ham')
这是测试代码,主要看中间用#注释的地方,如果就这样运行这段代码就会报错:
nboundLocalError: local variable 'state' referenced before assignment
但如果把#去掉就可以运行.他的作用一目了然.
再谈为什么要使用nonlocal,说实话我还是没看懂,不知道他到底要说什么.原文列举了3个原因:
1.与全局共享状态
def tester(start):
global state
state = start
def nested(label):
global state
print(label,state)
state += 1
return nested
原文:这样使用global,它只考虑到模块作用域中状态信息的单个共享副本--如果我们再次调用tester,将会重新设置模块的状态变量,以至于前面的调用将会看到自己的状态被覆盖
>>> def tester(start):
global state
state = start
def nested(label):
global state
print(label,state)
state += 1
return nested
>>> F= tester(0)
>>> F('spam')
spam 0
>>> F('eggs')
eggs 1
>>>
>>>
>>>
>>> G=tester(42)
>>> G('toast')
toast 42
>>> G('bacon')
bacon 43
>>> F('ham')
ham 44
>>>
三个空格之后的部分就是它所说的覆盖,
下面是使用nonlocal的情况:
>>> 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('eggs')
eggs 2
>>> G=tester(42)
>>> G('spam')
spam 42
>>> G('eggs')
eggs 43
>>> F('bacon')
bacon 3
也被覆盖了,所以不是很明白他说覆盖的意思