1
def counter(x):

    def _cnt():
        #nonlocal x
        x = x+1
        print(x)
        return x

    return _cnt
a = counter(0)
print(a())

上面的代码给出了以下错误

UnboundLocalError:分配前引用的局部变量“x”

为什么这不能在 _cnt 的命名空间中创建一个值为 'x+1' 的新对象并将其绑定到 x。我们将在两个函数命名空间中都有引用 x

4

2 回答 2

3

一旦您在给定范围内分配名称,在同一范围内对同一名称的所有引用都是本地的。因此x + 1无法评估(因为它试图引用 local x)。

因此这有效:

def f():
    x = 42
    def g():
        print(x)
    g()
f()

但这不会:

def f():
    x = 42
    def g():
        print(x)
        x = 42
    g()
f()

第一个print有这个字节码:

0 LOAD_GLOBAL              0 (print) 
3 LOAD_DEREF               0 (x) 
6 CALL_FUNCTION            1 
9 POP_TOP  

而第二个print有这个:

0 LOAD_GLOBAL              0 (print) 
3 LOAD_FAST                0 (x) 
6 CALL_FUNCTION            1 
9 POP_TOP 
于 2013-09-28T05:29:20.770 回答
1

作用的范围counter_cnt不一样。即使它们是嵌套的,也没关系。

所以xincounter中不存在_cnt。也许将它作为参数传递(或使用nonlocal,正如您似乎已经理解的那样)

于 2013-09-28T05:29:54.940 回答