Tôi đang gặp một vấn đề rất kỳ lạ trong trình trang trí Python 3.
Nếu tôi làm điều này:
def rounds(nr_of_rounds):
def wrapper(func):
@wraps(func)
def inner(*args, **kwargs):
return nr_of_rounds
return inner
return wrapper
nó hoạt động tốt. Tuy nhiên, nếu tôi làm điều này:
def rounds(nr_of_rounds):
def wrapper(func):
@wraps(func)
def inner(*args, **kwargs):
lst = []
while nr_of_rounds > 0:
lst.append(func(*args, **kwargs))
nr_of_rounds -= 1
return max(lst)
return inner
return wrapper
Tôi có:
while nr_of_rounds > 0:
UnboundLocalError: local variable 'nr_of_rounds' referenced before assignment
Nói cách khác, tôi có thể sử dụng nr_of_rounds
trong hàm bên trong nếu tôi sử dụng nó để trả về, nhưng tôi không thể làm gì khác với nó. Tại sao vậy?