python(第二天):global和nonlocal

在看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

也被覆盖了,所以不是很明白他说覆盖的意思

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值