如何在Python 2.X中也达到类似nonlocal关键字的效果
2024-08-27 21:19:37
nonlocal关键字时Python 3.X中引入的,目的是让内层函数可以修改外层函数的变量值,而该关键字在Python 2.X中是不存在的。那么,要在Python 2.X中达到类型达到类似nonlocal关键字的效果,有方法吗?
答案是肯定的,主要有如下四种方法:
1 将要改变的变量在外层函数声明成global的,这样内层函数就可以改变这个变量的值了,缺点就是所有内层函数都共享一个全局变量的值:
def test(start):
global state # 将state声明成全局变量
state = start def nested(label):
global state # 必须使用global再次声明,否则state += 1会报错,因此不使用global声明,Python认为state是在nested里面声明的一个局部变量,而这个变量没有被定义(即没有被赋值),就被拿来使用了
print(label, state)
state += 1 return nested >>>F = test(1)
>>>F('toast')
toast 1 >>> G = test(42)
>>>G('spam')
spam 42 >>>F('ham') # F和G都共享一个全局变量state,导致F的state变成了43
ham 43
2 使用class
class tester:
def __init__(self, start):
self.state = start
def nested(self, label):
print(label, self.state)
self.state += 1 >>>F = test(0)
>>>F.nested('spam')
spam 0
3 使用函数的属性,由于函数在Python里面是一个对象,因此可以给它添加属性,我们可以利用这一点达到目的
def tester(start):
def nested(label):
print(label, nested.state)
nested.state += 1
nested.state = start # state作为函数属性
return nested
4 利用可变的数据结构,比如数组,但是相比较使用class和函数的属性,这种使用方式很晦涩
def tester(start):
def nested(label):
print(label, state[0])
state[0] += 1
state = [start] # 通过数组达到这一目的
return nested
最新文章
- 我这么玩Web Api(一):帮助页面或用户手册(Microsoft and Swashbuckle Help Page)
- 安装KVM及虚拟机
- Zookeeper
- maven 编译项目时:报com.sun.image.codec.jpeg不存在
- SQL 数据库的使用
- CSS3秘笈第三版涵盖HTML5学习笔记1~5章
- OpenGL三维镂垫
- [转载]JQuery.closest(),parent(),parents()寻找父节点
- 【转】iOS-Core-Animation-Advanced-Techniques(一)
- 【翻译】A (very) short introduction to R R的简短介绍
- Find the largest multiple of 3 解答
- php Excel文件导入 Spreadsheet_Excel_Reader
- JQuery源码-------JQuery中数值型变量的判断isNumeric
- 钉钉授权第三方WEB网站扫码登录
- Luogu P3346 [ZJOI2015]诸神眷顾的幻想乡 广义SAM 后缀自动机
- javaweb简单的实现文件上传
- Facebook的一些基本操作(网页版)
- SSD卡对mongodb的影响
- Java Selenium - 元素定位(一)
- iOS 开发笔记-控制器tab切换view显示