我有一個python類的屬性,在大型數組上執行操作。每次訪問該屬性時,在不重做操作的情況下首次計算該方法後,如何存儲該方法結果的最佳方法是什麼?Pythonic的方法來存儲一個方法的結果作爲一個屬性
例如:
class MyClass:
def __init__(self, x, y):
"""Input variables are two large data arrays"""
self.x = x
self.y = y
@property
def calculate(self):
"""Some computationally expensive operation"""
try:
# the result has been calculated already
return self._result
except AttributeError:
# if not, calculate it
self._result = self.x * self.y
return self._result
用法:
>>> foo = MyClass(2,3)
>>> a = foo.calculate
>>> print(a)
6
正如你所看到的,我想出了到目前爲止是有一個「隱藏」屬性的結果存儲在哪裏。有一個更好的方法嗎?這裏使用的是@property
嗎?
謝謝。
退房https://github.com/pydanny/cached-property –
如何初始化的對象與'self._result = None',然後在'calculate'您先檢查是否'self._result '在計算新產品之前已經有了價值? – TigerhawkT3
我個人不會在這裏使用'@ property',因爲從邏輯上講,你期望稱爲「calculate」的東西是一個可以工作的函數。 – Paul