零基础学python-16.7 nonlocal介绍

这一章节我们来讨论一些nonlocal

1.nonlocal简介

nonlocal与global相似,但是它只是作用于嵌套作用域,而且只是作用在函数里面

>>> def test():
	x=1
	print("test:"+str(x))
	def test2():
		nonlocal x
		x=3
		print("test2:"+str(x))
	class a:
		nonlocal x
		x=5
		print("a:"+str(x))
		def a1():
			nonlocal x
			x=7
			print("a.a1:"+str(x))
	test2()
	a.a1()
	print("test:"+str(x))

	
>>> test()
test:1
a:5
test2:3
a.a1:7
test:7

从上面的代码可以得出前面的结论,大家也许会注意到,test里面有个class,而且它里面的nonlocal x起作用了,是不是相违背?

不是,因为它的最外层是def

我们给一个更加直接的代码:

>>> def test():
	x=1
	print("test:"+str(x))
	#def test2():
	#	nonlocal x
	#	x=3
	#	print("test2:"+str(x))
	class a:
		nonlocal x
		x=5
		print("a:"+str(x))
		def a1():
			nonlocal x
			x=7
			print("a.a1:"+str(x))
	#test2()
	a()
	print("test:"+str(x))

	
>>> test()
test:1
a:5
test:5
>>>

我们注释了一部分代码,而且不知道a里面的a1,这个时候我们看见,nonlocal也是起作用的


但是有一点需要注意的地方:(也是global与nonlocal的区别)

global可以从嵌套的作用域开始执行,但是nonlocal所声明的变量必须已经存在,不然会报错

>>> def test():
	global x

	
>>> def test():
	nonlocal x
	
SyntaxError: no binding for nonlocal 'x' found
>>>

2.应用

nonlocal主要用于修改外层函数的变量

看下面代码:

>>> def test():
	x=1
	print("test:"+str(x))
	def test2():
		#nonlocal x
		x=3
		print("test2:"+str(x))
	test2()
	return x

>>> test()
test:1
test2:3
1
>>>

如果没使用nonlocal,x是不会改变的

>>> def test():
	x=1
	print("test:"+str(x))
	def test2():
		nonlocal x
		x=3
		print("test2:"+str(x))
	test2()
	return x

>>> test()
test:1
test2:3
3


但是使用了nonlocal声明x,x在test2执行后,已经改变了状态


总结:这一章节主要讲述了nonlocal是什么,还讲述了nonlocal的简单应用


这一章节就说到这里,谢谢大家

------------------------------------------------------------------

点击跳转零基础学python-目录



版权声明:本文为博主原创文章,未经博主允许不得转载。

转载于:https://my.oschina.net/u/2325575/blog/507718

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值