【脚本语言系列】关于Python基础知识函数缓存,你需要知道的事
2017-07-14 14:25
991 查看
如何使用函数缓存(Function caching)
针对Python 2.x# -*- coding:utf-8 -*- # only for python2.x from functools import wraps def cache(func): memo = {} @wraps(func) def wrapper(*args): if args in memo: return memo[args] else: rv = function(*args) memo[args] = rv return rv return wrapper @cache def memoize(n): if n < 2: return n return fibonacci(n-1)+fibonacci(n-2) print fibonacci(25)
75025
针对Python 3.x
# -*- coding:utf-8 -*- # only for python3.x from functools import lru_cache @lru_cache(maxsize=32) def fib(n): if n<2: return n return fib(n-1)+fib(n-2) print ([fib(n) for n in range(10)]) fib.cache_clear()
--------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-8-566ab65dd9bc> in <module>() 1 ----> 2 from functools import lru_cache 3 4 @lru_cache(maxsize=32) 5 def fib(n): ImportError: cannot import name lru_cache
什么是函数缓存(Function caching)
缓存给定参数的返回值;为何使用函数缓存(Function caching)
频繁调用特定参数的函数的情况下,节省时间;相关文章推荐
- 【脚本语言系列】关于Python基础知识兼容Python 2.x+Python 3.x,你需要知道的事
- 【脚本语言系列】关于Python基础知识装饰器,你需要知道的事
- 【脚本语言系列】关于Python基础知识Lambda表达式,你需要知道的事
- 【脚本语言系列】关于Python基础知识映射器和过滤器,你需要知道的事
- 【脚本语言系列】关于Python基础知识枚举,你需要知道的事
- 【脚本语言系列】关于Python基础知识推导式,你需要知道的事
- 【脚本语言系列】关于Python基础知识魔法变量,你需要知道的事
- 【脚本语言系列】关于Python基础知识多返回值,你需要知道的事
- 【脚本语言系列】关于Python基础知识处理字符串,你需要知道的事
- 【脚本语言系列】关于Python基础知识文件操作,你需要知道的事
- 【脚本语言系列】关于Python基础知识__slots__,你需要知道的事
- 【脚本语言系列】关于Python基础知识面向对象编程,你需要知道的事
- 【脚本语言系列】关于Python基础知识异常处理,你需要知道的事
- 【脚本语言系列】关于Python基础知识设计模式,你需要知道的事
- 【脚本语言系列】关于Python基础知识容器,你需要知道的事
- 【脚本语言系列】关于Python基础知识迭代器,你需要知道的事
- 【脚本语言系列】关于Python基础知识调试,你需要知道的事
- 【脚本语言系列】关于Python基础知识对象自省,你需要知道的事
- 【脚本语言系列】关于Python基础知识协程,你需要知道的事
- 【脚本语言系列】关于Python基础知识对象变动,你知道的事