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

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

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

安装functools

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

pip install functools
Bash

导入functools

要导入functools –

import functools
Bash

让我们逐一理解两个缓存方法 –

cached_property()

对于实例的昂贵计算属性非常有用,因为这些属性在其他方面是有效不可变的。

cached_property方法只适用于不带任何参数的方法。它不会创建对实例的引用。缓存的方法结果仅在实例存活时保留。

优点是当实例不再使用时,缓存的方法结果将立即释放。缺点是如果实例积累,则方法结果也会积累。它们可以无限增长。

示例

让我们看一个示例 –

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

lru_cache

lru_cache方法适用于具有可哈希参数的方法。它会创建对实例的引用,除非特殊的努力传递弱引用。

最近最少使用算法的优点是缓存由指定的maxsize界定。缺点是实例保持存活直到它们过时或者缓存被清除。

示例

让我们看一个示例 –

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

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

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())
Bash

输出

[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)
Bash

缓存示例

现在,让我们看一下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.
Bash

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册