【发布时间】:2020-07-08 13:33:34
【问题描述】:
我正在尝试学习如何在 Python 中使用装饰器,但这是一项具有挑战性的任务。我制作了一个装饰器,它假设执行指定次数的装饰函数。我已设法生成执行此任务的代码:
def repeat(num_times):
def decorator_repeat(func):
def wrapper_repeat(x):
for _ in range(num_times):
func(x)
return wrapper_repeat
return decorator_repeat
@repeat(4)
def helloWorld(say):
print(say)
helloWorld("Hey everyone!")
然后,我再次尝试重现这段代码,但这次我使用了while循环而不是for循环,如下所示:
def repeat(num_times):
def decorator_repeat(func):
def wrapper_repeat(x):
while num_times > 0:
func(x)
num_times -= 1
return wrapper_repeat
return decorator_repeat
@repeat(4)
def helloWorld(say):
print(say)
helloWorld("Hey everyone!")
但现在函数返回错误。
Traceback (most recent call last):
File "untitled.py", line 118, in <module>
helloWorld("Hey everyone!")
File "untitled.py", line 108, in wrapper_repeat
while num_times > 0:
UnboundLocalError: local variable 'num_times' referenced before assignment
对我来说,这些功能应该是相同的,但事实并非如此。你能帮我理解我的代码有什么问题吗?
谢谢!
【问题讨论】:
标签: python python-3.x loops python-decorators