Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何从嵌套闭包修改局部变量?_Python 3.x_Functional Programming_Closures_Nested Function - Fatal编程技术网

Python 3.x 如何从嵌套闭包修改局部变量?

Python 3.x 如何从嵌套闭包修改局部变量?,python-3.x,functional-programming,closures,nested-function,Python 3.x,Functional Programming,Closures,Nested Function,考虑以下代码示例: 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

考虑以下代码示例:

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
回溯(最近一次呼叫最后一次):
文件“/Users/cls/workspace/PLPcython/src/sandbox.py”,第23行,在
testClosure()
testClosure中第18行的文件“/Users/cls/workspace/PLPcython/src/sandbox.py”
增量()
文件“/Users/cls/workspace/PLPcython/src/sandbox.py”,第15行,增量
计数+=1
UnboundLocalError:赋值前引用的局部变量“count”
我习惯用C++编写这样的代码:

void testClosure() {
    int count = 0

    auto increment = [&](){
        count += 1;
    };

    for (int i = 0; i < 10; ++i) {
        increment();
    }

}
void testClosure(){
整数计数=0
自动递增=[&](){
计数+=1;
};
对于(int i=0;i<10;++i){
增量();
}
}

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

如果您这样做,我会让它正常工作:

def testClosure():
    count = 0

    def increment():
        nonlocal count
        count += 1

    for i in range(10):
        increment()

    print(count)
testClosure()

请注意,这只适用于Python 3.x,但您显然正在使用它,因此这不是一个问题。

很抱歉,有没有一个现实世界的例子可以说明这一点,但这个玩具示例更容易理解和解决实际问题。我的问题基本上是通过提到Python 3的
非本地
关键字来回答的,我不知道这个关键字。@JakobBowyer真实世界示例: