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


快取方法的兩種工具是`functools.cached_property()`和`functools.lru_cache()`。這兩個模組都是`functools`模組的一部分。`functools`模組用於高階函式:作用於其他函式或返回其他函式的函式。讓我們首先安裝並匯入`functools`模組:

安裝functools

要安裝`functools`模組,請使用pip:

pip install functools

匯入functools

要匯入`functools`:

import functools

讓我們逐一瞭解這兩種快取方法:

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)

lru_cache

`lru_cache`方法適用於具有可雜湊引數的方法。除非採取特殊措施傳入弱引用,否則它會建立對例項的引用。

最近最少使用演算法的優點是快取受指定的`maxsize`限制。缺點是例項將一直保留,直到它們從快取中過期或快取被清除。

示例

讓我們看一個例子:

@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)

快取示例

現在,讓我們看一個`functools.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.

更新於:2022年9月19日

2K+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告