我正在尝试在Python 3中创建一个冷却器装饰器。理想用法如下:
@cooldown(duration=2)
def func(string):
print(string)
然后...
func('1st attempt') # should work (as cooldown == 0) and reset cooldown (cooldown = 2)
func('2nd attempt') # should fail (as cooldown != 0)
func.update_cooldown() # should decrease cooldown (cooldown -= 1)
func('3rd attempt') # should also fail (as cooldown != 0)
func.update_cooldown() # should decrease cooldown (cooldown -= 1)
func('4th attempt') # should work (as cooldown == 0) and reset cooldown (cooldown = 2)
我的代码(Python 3.8):
import functools
def cooldown(duration):
def decorator(method):
cooldown = 0
@functools.wraps(method)
def wrapper(*args,**kwargs):
nonlocal cooldown
if cooldown <= 0:
cooldown = duration
return method(*args,**kwargs)
print(f'Cooldown active,{cooldown} updates remaining')
return wrapper
return decorator
我将如何添加减少特定装饰功能的冷却时间的功能?以及如何使它适应类方法?
谢谢!