首页 > 解决方案 > 如何在 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的不同吗?

标签: pythonschemestatesicpmutation

解决方案


我似乎找到了问题的答案。我尽可能地将代码翻译成 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]

推荐阅读