我有以下装饰器(根据https://realpython.com/primer-on-python-decorators/#decorators-with-arguments):
def slow_down(_func=None, rate = 1):
def decorator(func):
print(_func) # Added for understanding?
@functools.wraps(func)
def wrapper(*args, **kwargs):
time.sleep(rate)
return func(*args, **kwargs)
return wrapper
if _func==None:
return decorator
else: return decorator(_func)
我的问题是,这个slow_down
函数不应该用初始化_func = None
吗?但是,当我用装饰器创建一个函数时,我得到了一个初始化的 _func 值:
@slow_down
def countdown(time = 5):
print(time)
if time == 0: pass
else: countdown(time-1)
<function countdown at 0x7f1aa0a8da60>
但是当我初始化函数的值时,我得到None
:
@slow_down(rate=2)
def countdown(time = 5):
print(time)
if time == 0: pass
else: countdown(time-1)
None
不应该反过来吗?
当您为装饰器使用裸名称时(如在@slow_down 中),它会以被装饰为参数的函数被调用。当涉及括号时(如第二种情况),装饰器被调用,并期望返回另一个函数,该函数被调用,该函数被装饰为参数。您的特定装饰器中的 if 允许它以任何一种方式工作。– 杰森哈珀
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句