4 回答

TA貢獻1877條經驗 獲得超6個贊
由于我們只需要執行該函數一次,但我們不知道是否function_1首先執行function_2,因此可以使用以下想法:
compute如果可能,您可以在方法本身中調用該函數init。
def __init__(self, params):
....
self._compute_start_end()
def _compute_start_end(self):
....
self.start, self.end = start, end
def function_1(self):
#use self.start and self.end
def function_2(self):
#use self.start and self.end instead of recomputing
如果該聲明由于某種原因不適用于您的程序,您可以使用簡單的檢查來檢查該函數是否已被調用。
def __init__(self, params):
....
self.start, self.end = None, None
def _compute_start_end(self):
if (self.start or self.end):
return
....
self.start, self.end = start, end
def function_1(self):
self._compute_start_end()
#use self.start and self.end
def function_2(self):
self._compute_start_end()
#use self.start and self.end instead of recomputing
只要您不None同時分配start和end,計算就只會發生一次。

TA貢獻1906條經驗 獲得超10個贊
好的。其他人這樣做是作為答案而不是評論。我也把我的放在這里吧
我更喜歡
@functools.lru_cache(None) def _compute_start_end(self): ....
并完成它。
所有其他解決方案都是正確的,但它們依賴于程序員記住在調用或_compute_start_end
之前調用一次。告訴 Python 僅緩存結果使得此代碼對未來的更改更具彈性。_function_1
_function_2
_compute_start_end

TA貢獻1886條經驗 獲得超2個贊
如果您不想重新計算“開始,結束”,那么只需將它們作為實例變量即可
self.start = #Some Value
self.end = #Some Value
然后,當您在調用 function_1 之后調用 function_2 時,您可以執行類似的操作
def _fuction_2(self):
start, end = self.start, self.end

TA貢獻1829條經驗 獲得超6個贊
有幾種方法可以做到這一點。
在類中存儲值
這可能是您可以做的最基本的事情:僅存儲start并end放在類中。有時這稱為“延遲初始化”。
class Problem:
? ? def __init__(self):
? ? ? ? self._start, self._end = None, None
? ? def _compute_start_end(self):
? ? ? ? if not self._start and not self._end:
? ? ? ? ? ? self._start, self._end = real_compute()
? ? ? ? return self._start, self._end
? ? def _function1(self):
? ? ? ? start, end = self._compute_start_end()
? ? def _function2(self):
? ? ? ? start, end = self._compute_start_end()
或者,您可以在構造函數中計算_startand _end。
class Problem:
? ? def __init__(self):
? ? ? ? self._start, self._end = self._compute_start_end()
? ? def _compute_start_end(self):
? ? ? ? ...
? ? ? ? return computed_start, computed_end
? ? def _function1(self):
? ? ? ? foo(self._start, self._end)
? ? def _function2(self):
? ? ? ? bar(self._start, self._end)
記憶
您還可以使用一種稱為“memoization”的技術,該技術在 Python 中以functools.lru_cache
.?這基本上會記住帶有一組參數的函數調用結果,緩存并返回它而不是運行該函數。
如果您不想讓人造成員弄亂您的班級,那么這很好。
from functools import lru_cache
class Problem:
? ? @lru_cache
? ? def _compute_start_end(self):
? ? ? ? ...
? ? ? ? return start, end
如果您使用 Python 3.9,您還可以使用functools.cache
,它是lru_cache
.
添加回答
舉報