Python 之nonlocal 关键字

nonlocal 关键字 作用:用来修改局部变量

  • nonlocal 修改局部变量时,采用LEGB原则

    1. 跳出当前函数这一层空间,到上一层寻找
    2. 如果上一层不存在该变量,继续向上一层寻找
    3. 如果最顶级也找不到了,直接报错
    • 当前函数空间如果找不到,跳出这一层,到上一层寻找 [nonlocal 修改局部变量]
      def outer():
      	a = 1
      	def inner():
      		nonlocal a               # 用来修改当前空间上一层的局部变量
      		a = 2
      		print(a)
      	inner()
      	print(a)
      outer()
      
      # 21
      # 12
      # 11
      # 22
      
    • 如果上一层不存在该变量,继续向上一层寻找
      a = 300
      def outer():
      	a = 200
      	def inner():
      		a = 100
      		def smaller():
      			nonlocal a
      			a = 400
      		smaller()
      		print(a)
      	inner()
      	print(a)
      outer()
      print(a)                          # 400 200 300 
      
      升级
      a = 300
      def outer():
      	a = 200
      	def inner():
      		def smaller():
      			nonlocal a
      			a = 400
      		smaller()
      		print(a)
      	inner()
      	print(a)
      outer()
      print(a)                        # 400 400 300
      
    • 如果最顶级也找不到了,直接报错
      a = 200          # 全局变量,nonlocal无法更改全局变量,只能该局部变量,global关键字更改全局变量
      def outer():
      	def inner():
      		def smaller():
      			nonlocal a
      			a = 400
      		smaller()
      		print(a)
      	inner()
      	print(a)
      outer()                          # error 报错
      
    • 不依赖局部nonlocal ,如何改变局部变量呢? 通过列表~
      def outer():
      	lst = [1,2,3]                # 定义一个列表
      	def inner():
      		lst[-1] = 100		
      	inner()
      	print(lst)
      outer()
      
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值