使用python装饰器的计时器倒计时

使用python装饰器的计时器倒计时,python,decorator,Python,Decorator,我试图做一个倒计时功能,但在每个使用装饰器的输出之间有2秒的睡眠时间。目前它不工作。我错过了什么 import time def sleep_dec(function): def wrapper(*args, **kwargs): time.sleep(2) return function(*args, **kwargs) return wrapper @sleep_dec def countdown(n): while n > 0: print(

我试图做一个倒计时功能,但在每个使用装饰器的输出之间有2秒的睡眠时间。目前它不工作。我错过了什么

import time

def sleep_dec(function):
  def wrapper(*args, **kwargs):
    time.sleep(2)
    return function(*args, **kwargs)
  return wrapper


@sleep_dec
def countdown(n):
  while n > 0:
    print(n)
    n -= 1
print(countdown(5))
n-=1
将永远无法到达。实际上,
while
循环只会迭代一次,函数只返回
n

您想改用
yield

但是,它仍然不起作用。相反,您将在调用
倒计时
之前暂停2秒,但不是在每次迭代之间

在这个用例中,我甚至不会使用装饰器,而只是一个默认参数:

def countdown(n):
    while n > 0:
        return n
        n -= 1
如果您坚持使用装饰器,请编辑。请注意,这是次优的(没有太多意义),我不会在生产代码中使用它:

def countdown(n, wait=None):
    while n > 0:
        if wait:
            time.sleep(wait)
        yield n
        n -= 1

# no sleep between iterations
for i in countdown(5):
     print(i)

# 2 seconds sleep between every iteration
for i in countdown(5, wait=2):
     print(i)

谢谢你的等待方法…但是我特别想找一个decorator方法。在这个例子中,decorator看起来有点过分了。但它是有效的。
import time

def sleep_dec(function):
    def wrapper(*args):
        return function(*args, wait=2)
    return wrapper

@sleep_dec
# it might make more sense to accept **kwargs instead of wait=None
def countdown(n, wait=None):
    while n > 0:
        if wait:
            time.sleep(wait)
        yield n
        n -= 1

# 2 seconds sleep between each iteration
for i in countdown(5):
     print(i)