python - 如何在 python 中将状态变量保留在两个级别?
问题描述
方案中有这段代码(来自伯克利的旧 SICP 课程),它创建了一个计数器函数,将局部状态变量保留在两个级别,类似于类变量和实例变量。
(define make-count
(let ((glob 0))
(lambda ()
(let ((loc 0))
(lambda ()
(set! loc (+ loc 1))
(set! glob (+ glob 1))
(list loc glob))))))
(define c1 (make-count))
(define c2 (make-count))
(c1) ; (1 1)
(c1) ; (2 2)
(c2) ; (1 3)
(c2) ; (2 4)
我找不到在 python 中类似于此功能的方法。作为一个例子,我写了这个做错事的代码:
def make_counter():
glob = 0
def a():
loc = 0
def b():
nonlocal glob, loc
loc += 1
glob += 1
return [loc, glob]
return b
return a()
c1 = make_counter()
c2 = make_counter()
c1() # [1, 1]
c1() # [2, 2]
c2() # [1, 1]
c2() # [2, 2]
我知道 python 中没有“让”功能,但是,我做错了什么。python中的环境模型与scheme的不同吗?
解决方案
我似乎找到了问题的答案。我尽可能地将代码翻译成 python,但仍然对它的工作原理感到困惑。
任何解释都会被应用。
def make_counter_helper():
glob = 0
def a():
loc = 0
def counter():
nonlocal loc, glob
glob += 1
loc += 1
return [loc, glob]
return counter
return a
make_counter = make_counter_helper()
c1 = make_counter()
c2 = make_counter()
c1() # [1, 1]
c1() # [2, 2]
c2() # [1, 3]
c2() # [2, 4]
推荐阅读
- delphi - 使用 TStreamReader 和 TStringList 处理非常大的文本文件
- javascript - 如何在 Node.js 中为集成测试和微服务创建架构
- r - 将每个 ID 的每日值汇总为每周平均值
- android - Cardview 上的评分栏不显示
- python - Plot.ly:具有共享 X 轴的子图的不同高度
- android - OnSharedPreferenceChangeListener 的问题
- java - 使用复合键审计多对多连接
- python - “按位置选择”工具的arcpy命令?
- php - 从 SHOW TABLES 查询中打印值
- angular - “找不到模块:错误:无法解决...”错误背后的机制如何工作