【问题标题】:How to modify local variables from a nested closure? [duplicate]如何从嵌套闭包修改局部变量? [复制]
【发布时间】:2013-07-17 13:52:50
【问题描述】:

考虑以下代码示例:

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 vs C++)吗?

【问题讨论】:

  • 抱歉有点丢了,有没有实际有用的真实示例?
  • @JakobBowyer 是的,但是这个玩具示例更容易理解和解决实际问题。
  • 我的问题基本上是通过提到Python 3的nonlocal关键字来回答的,我不知道。

标签: python-3.x functional-programming closures nested-function


【解决方案1】:

如果你这样做,我会成功:

def testClosure():
    count = 0

    def increment():
        nonlocal count
        count += 1

    for i in range(10):
        increment()

    print(count)
testClosure()

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-29
    • 1970-01-01
    • 2016-11-12
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    • 2018-12-24
    相关资源
    最近更新 更多