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

时间:2016-06-13 09:51:52

标签: python decorator

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))

尝试使用装饰器进行倒计时功能但每次输出之间的睡眠时间为2秒。目前它不起作用。我在这里缺少什么?

1 个答案:

答案 0 :(得分:1)

def countdown(n):
    while n > 0:
        return n
        n -= 1
永远不会达到

n -= 1。事实上,while循环只会迭代一次而你的函数只返回n

您想改用yield

但是,它仍然无效。相反,你会在调用countdown之前获得2秒的暂停,但不会在每次迭代之间获得暂停。

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

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)

编辑如果您坚持使用装饰器。请注意,这是次优的(并没有多大意义),我不会在生产代码中使用它:

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)