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

最新文章

  1. 我这么玩Web Api(一):帮助页面或用户手册(Microsoft and Swashbuckle Help Page)
  2. 安装KVM及虚拟机
  3. Zookeeper
  4. maven 编译项目时:报com.sun.image.codec.jpeg不存在
  5. SQL 数据库的使用
  6. CSS3秘笈第三版涵盖HTML5学习笔记1~5章
  7. OpenGL三维镂垫
  8. [转载]JQuery.closest(),parent(),parents()寻找父节点
  9. 【转】iOS-Core-Animation-Advanced-Techniques(一)
  10. 【翻译】A (very) short introduction to R R的简短介绍
  11. Find the largest multiple of 3 解答
  12. php Excel文件导入 Spreadsheet_Excel_Reader
  13. JQuery源码-------JQuery中数值型变量的判断isNumeric
  14. 钉钉授权第三方WEB网站扫码登录
  15. Luogu P3346 [ZJOI2015]诸神眷顾的幻想乡 广义SAM 后缀自动机
  16. javaweb简单的实现文件上传
  17. Facebook的一些基本操作(网页版)
  18. SSD卡对mongodb的影响
  19. Java Selenium - 元素定位(一)
  20. iOS 开发笔记-控制器tab切换view显示

热门文章

  1. QT 防止FTP 上传软件在断连处 Crash
  2. Dubbo 安装监控中心
  3. JavaScript中Array的正确使用方式
  4. python的基本知识
  5. 大数据学习--day11(抽象类、接口、equals、compareTo)
  6. Django的安装创建与连接数据库
  7. 主存和cache的地址映射
  8. HCA数据下载
  9. 北京Uber优步司机奖励政策(3月24日)
  10. 青岛Uber优步司机奖励政策(1月11日~1月17日)