2017-04-21 17 views
1

私はPythonでデコレータのロジックを理解しようとしていますが、ローカル変数のスコープに問題があります。
CODE:Pythonデコレータスコープ

# version #1 
def decorator(function): 
    counter = 0 
    def wrapper(): 
     print(counter) 
     function() 
     return counter 
    return wrapper 

# version #2 
def decorator(function): 
    counter = 0 
    def wrapper(): 
     counter += 1 
     function() 
     return counter 
    return wrapper 

@decorator 
def function(): 
    print("Printed from function().") 

function() 

私の質問は、なぜ#1作品やcounterが印刷されているが、私は#2counterを変更しようとすると、私はUnboundLocalError: local variable 'counter' referenced before assignmentを取得しますか?
ありがとうございます!

答えて

-1

counter += 1は、その時点で未結合である1+ counterに等しい変数counterを定義counter = counter + 1の糖です。