2017-04-21 168 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被打印出來,但是當我嘗試在#2改變counter,我得到UnboundLocalError: local variable 'counter' referenced before assignment
謝謝!

回答

-1

counter += 1counter = counter + 1的糖,其定義變量counter等於1+ counter,其在此時未綁定。