1

次のコード例を検討してください。

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++)?

4

1 に答える 1

2

あなたがこれを行うと、私はそれを働かせました:

def testClosure():
    count = 0

    def increment():
        nonlocal count
        count += 1

    for i in range(10):
        increment()

    print(count)
testClosure()

これは Python 3.x でのみ機能することに注意してください。ただし、明らかにそれを使用しているため、問題にはなりません。

于 2013-07-18T14:47:18.253 に答える