from functools import lru_cache
@lru_cache(maxsize=1, typed=True)
def func(s):
print(s)
return s
func(1)
1
Out[4]: 1
func(1)
Out[5]: 1
func(2)
2
Out[6]: 2
func(2.0)
2.0
Out[7]: 2.0
- 不难看出 第一次调用func 传入1 是既打印了1 又返回了1 第二次调用相同的func 传入1时,未打印 只返回
- 传入2.0 和2的会被认为是不同的调用,刷新缓存
- lru_cache 的参数maxsize 代表能缓存几个函数执行的结果 typed代表是否参数类型改变时是否重新缓存
本文通过一个简单的Python示例介绍了functools模块中lru_cache装饰器的基本使用方法。该装饰器能够为函数调用提供缓存机制,提高程序运行效率。文章解释了maxsize参数控制缓存大小及typed参数决定是否区分参数类型的细节。
947

被折叠的 条评论
为什么被折叠?



