这是我参与「第五届青训营 」伴学笔记创作活动的第 17 天
-
Python 内置模块 functools 提供的高阶函数
@functools.cache是简单轻量级无长度限制的函数缓存,这种缓存有时称为 "memoize"(记忆化)。它是 3.9 新版功能,是在 lru_cache 缓存基础上简化了的对无限长度缓存 -
用法:
@cache def factorial(n): return n * factorial(n-1) if n else 1 >>> factorial(10) # no previously cached result, makes 11 recursive calls 3628800 >>> factorial(5) # just looks up cached value result 120 >>> factorial(12) # makes two new recursive calls, the other 10 are cached 479001600 -
应用实例: