首頁  >  文章  >  後端開發  >  如何在Python中快取方法呼叫?

如何在Python中快取方法呼叫?

王林
王林轉載
2023-09-10 17:37:02665瀏覽

如何在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.

以上是如何在Python中快取方法呼叫?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除