代码点读机 / Python / functools

functools Python · 常用模块

给函数加功能的工具包,比如缓存结果、固定参数。

怎么用

from functools import lru_cache

小例子

from functools import lru_cache
@lru_cache
def f(n):
    return n if n < 2 else f(n-1)+f(n-2)
print(f(5))

运行结果

5

提醒:缓存能加速重复计算。

官方文档:https://docs.python.org/zh-cn/3/library/functools.html

在代码里遇到不认识的词?打开代码点读机,点一下就懂 → ← Python全部词条