• 零基础学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-目录



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

  • 相关阅读:
    【数据结构】KMP算法
    【数据结构】银行问题
    ejs模板渲染页面
    node的知识点
    http搭建服务器
    http接收页面传递的数据
    http模块
    node的http模块
    node的fs模块
    base.css
  • 原文地址:https://www.cnblogs.com/raylee2007/p/4896735.html
Copyright © 2020-2023  润新知