如何创建冷却时间

2024-06-16 08:46:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在python3中创建一个冷却装饰器。理想用法如下:

@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

如何为特定的装饰函数添加减少冷却计数器的功能?我将如何调整它以使用类方法?

提前谢谢


Tags: andstringreturndefas装饰methodwork
1条回答
网友
1楼 · 发布于 2024-06-16 08:46:55
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")

        def update_cooldown():
            nonlocal cooldown
            cooldown -= 1

        wrapper.update_cooldown = update_cooldown
        return wrapper

    return decorator

cooldown变量对于每个修饰函数都是唯一的,因为在每个cooldown调用中都定义了新的修饰函数def decorator(method):,并在其中定义了新的cooldown counter

它已经适用于类方法:

class A:
    @classmethod
    @cooldown(duration=2)
    def a(cls):
        print("whatever")

A.a() # whatever
A.a() # Cooldown active, 2 updates remaining
A.a.update_cooldown() 
A.a() # Cooldown active, 1 updates remaining

相关问题 更多 >