卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章19013本站已运行342

如何在Python中缓存方法调用?

如何在Python中缓存方法调用?

用于缓存方法的两个工具是 functools.cached_property() 和 functools.lru_cache()。这两个模块都是 functools 模块的一部分。 functools 模块用于高阶函数:作用于或返回其他函数的函数。让我们首先安装并导入 functools 模块 -

安装 functools

要安装functools模块,请使用pip −

'
pip install functools

导入函数工具

要导入functools −

'
import functools

让我们一一了解缓存 -

cached_property()

对于实例的昂贵计算属性很有用,否则这些属性实际上是不可变的。

cached_property 方法仅适用于不带任何参数的方法。它不会创建对实例的引用。仅当实例处于活动状态时,才会保留缓存的方法结果。

这样做的好处是当实例不再使用时,缓存的方法结果会立即释放。缺点是如果实例累积,累积的方法结果也会累积。他们可以无限制地成长。

Example

的中文翻译为:

示例

让我们看一个例子 -

'
class DataSet:
   def __init__(self, sequence_of_numbers):
      self._data = tuple(sequence_of_numbers)
   @cached_property
   def stdev(self):
      return statistics.stdev(self._data)

lru_cache

lru_cache 方法适用于具有可散列参数的方法。除非特别努力传递弱引用,否则它会创建对实例的引用。

最近最少使用算法的优点是缓存受到指定的最大大小的限制。缺点是实例会一直保持活动状态,直到它们从缓存中过期或者缓存被清除。

Example

的中文翻译为:

示例

让我们看一个例子 -

'
@lru_cache
def count_vowels(sentence):
   return sum(sentence.count(vowel) for vowel in 'AEIOUaeiou')

使用缓存计算斐波那契数的示例 −

'
from functools import lru_cache

@lru_cache(maxsize=None)
def fib(n):
   if n < 2:
      return n
   return fib(n-1) + fib(n-2)

print([fib(n) for n in range(16)])
print(fib.cache_info())

输出

'
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)

缓存示例

现在,让我们看一下 functool cached_property() 和 lru_cache 的完整示例 -

'
from functools import lru_cache
from functools import cached_property

class Weather:
   "Lookup weather information on a government website"
   def __init__(self, station_id):
      self._station_id = station_id
      # The _station_id is private and immutable
   
   def current_temperature(self):
      "Latest hourly observation"
      # Do not cache this because old results
      # can be out of date.

   @cached_property
   def location(self):
      "Return the longitude/latitude coordinates of the station"
      # Result only depends on the station_id
   @lru_cache(maxsize=20)
   def historic_rainfall(self, date, units='mm'):
      "Rainfall on a given date"
      # Depends on the station_id, date, and units.
卓越飞翔博客
上一篇: PHP7底层开发原理权威指南:了解PHP的解释和编译过程
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏