使用 python 装饰器的计时器倒计时
Countdown with timer using 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 秒。目前它不工作。我在这里错过了什么?
def countdown(n):
while n > 0:
return n
n -= 1
n -= 1
永远达不到。事实上,while
循环只会迭代一次,您的函数只是 return 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)
EDIT 如果你坚持使用装饰器。请注意,这是次优的(并且没有多大意义),我不会在生产代码中使用它:
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)
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 秒。目前它不工作。我在这里错过了什么?
def countdown(n):
while n > 0:
return n
n -= 1
n -= 1
永远达不到。事实上,while
循环只会迭代一次,您的函数只是 return 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)
EDIT 如果你坚持使用装饰器。请注意,这是次优的(并且没有多大意义),我不会在生产代码中使用它:
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)