前段时间面试python岗位,遇到一个问题,如何限制函数在指定时间内只运行一次?这个问题考得的python修饰函数。
解决方法如下:
import time
from datetime import datetime
from datetime import timedelta
def timeguard(time_interval, default=None):
def decorator(function):
# For first time always run the function
function.__last_run = datetime.min
def guard(*args, **kwargs):
now = datetime.now()
if now - function.__last_run >= time_interval:
function.__last_run = now
return function(*args, **kwargs)
elif default is not None:
return default(*args, **kwargs)
return guard
return decorator
if __name__ == "__main__":
@timeguard(timedelta(seconds=4),None)
def add():
print 12
add()
add()
add()
网友评论
请问在此代码中为何在执行第二遍add()的时候function.__last_run = datetime.min没有被执行而直接进入guard中的代码?
Python新手,谢谢!