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
?
謝謝!