Python笔记之nonlocal语句

本文详细解析了Python中的nonlocal语句,对比了其与global语句的区别,通过实例展示了如何在嵌套函数中正确修改外部变量,避免UnboundLocalError错误,实现变量在不同作用域间的有效共享。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

nonlocal语句

nonlocal语句和global是近亲。它和global的不同之处在于,nonlocal应用于一个嵌套的函数的作用域中修改名称,而不是所有def之外的全局模块作用域;而且在声明nonlocal名称的时候,它必须已经存在于该嵌套函数的作用域中——它们可能只存在于嵌套的函数中,并且不能由一个嵌套的def中的第一次赋值创建。

 

nonlocal应用

我们先来看一些nonlocal的例子

#示例1
>>> def tester(start):
...     state = start
...     def nested(label):
...         print(label,state)
...     return nested
...
>>> F = tester(0)
>>> F('spam')
spam 0

#尝试在嵌套的def内修改state
>>> def tester(start):
...     state = start
...     def nested(label):
...         print(label,state)
...         state += 1
...     return nested
...
>>> F = tester(0)
>>> F('spam')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in nested
UnboundLocalError: local variable 'state' referenced before assignment

使用nonlocal进行修改后:

#示例2
>>> 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('YAMAHA')
YAMAHA 2
>>> G = tester(45) 
>>> G('China')
China 45
>>> F('re')
re 3

注意:

  1. nonlocal语句允许在内存中保存可变状态的副本,并且解决了在类无法保证的情况下简单的状态保存。(在示例2中有这样的体现)
  2. 当执行一条nonlocal语句时,nonlocal名称必须已经在一个嵌套的def作用域中赋值过,否则将会得到一个错误——不能通过在嵌套的作用域给它们一个新值来创建它们(即边界情况)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值