本篇文章扣丁学堂 Python 培训小编和大家分享一下 Python 在线视频: Python 限制函数调用次数的实例, 对 Python 感兴趣的小伙伴就随着小编一起来了解一下吧.
扣丁学堂 Python 在线视频
博客中指定的是缓存, 我这里换成限制访问次数, 异曲同工:
- #newtest.py
- #!/usr/bin/env python
- #-*- coding:utf-8 -*-
- import time
- def stat_called_time(func):
- cache={
- }
- limit_times=[10]
- def _called_time(*args,**kwargs):
- key=func.__name__
- if key in cache.keys():
- [call_times,updatetime]=cache[key]
- if time.time()-updatetime <60:
- cache[key][0]+=1
- else:
- cache[key]=[1,time.time()]
- else:
- call_times=1
- cache[key]=[call_times,time.time()]
- print('调用次数: %s' % cache[key][0])
- print('限制次数: %s' % limit_times[0])
- if cache[key][0] <= limit_times[0]:
- res=func(*args,**kwargs)
- cache[key][1] = time.time()
- return res
- else:
- print("超过调用次数了")
- return None
- return _called_time
- @stat_called_time
- def foo():
- print("I'm foo")
- if __name__=='__main__':
- for i in range(10):
- foo()
- #test.py
- from newtest import foo
- import time
- for i in range(30):
- foo()
- print('*'*20)
- foo()
- foo()
- print('*'*20)
- for i in range(60):
- print(i)
- time.sleep(1)
- for i in range(11):
- foo()
以上就是扣丁学堂 Python 在线学习给大家分享的 Python 限制函数调用次数的实例讲解, 希望对小伙伴所有帮助. 想要了解更多内容的小伙伴可以登录扣丁学堂官网咨询. 扣丁学堂是专业的 Python 培训班, 不仅有专业的老师和与时俱进的课程体系, 还有大量的 Python 视频教程供学员观看学习哦.
来源: http://www.jianshu.com/p/731f09ab21d3