如何从嵌套闭包中修改局部变量



考虑以下代码示例:

def testClosure():
    count = 0
    def increment():
        count += 1
    for i in range(10):
        increment()
    print(count)    

调用此结果:

Traceback (most recent call last):
  File "/Users/cls/workspace/PLPcython/src/sandbox.py", line 23, in <module>
    testClosure()
  File "/Users/cls/workspace/PLPcython/src/sandbox.py", line 18, in testClosure
    increment()
  File "/Users/cls/workspace/PLPcython/src/sandbox.py", line 15, in increment
    count += 1
UnboundLocalError: local variable 'count' referenced before assignment

我习惯于用C++编写这样的代码:

void testClosure() {
    int count = 0
    auto increment = [&](){
        count += 1;
    };
    for (int i = 0; i < 10; ++i) {
        increment();
    }
}

我做错了什么?难道不能从内部函数修改外部函数的局部变量吗?这些是不同类型的闭包吗(Python和C++)?

如果你这样做,我就可以工作了:

def testClosure():
    count = 0
    def increment():
        nonlocal count
        count += 1
    for i in range(10):
        increment()
    print(count)
testClosure()

请注意,这只适用于Python3.x,但您显然正在使用它,所以这不是问题。

最新更新