4 回答

TA貢獻(xiàn)1877條經(jīng)驗(yàn) 獲得超6個贊
由于我們只需要執(zhí)行該函數(shù)一次,但我們不知道是否function_1首先執(zhí)行function_2,因此可以使用以下想法:
compute如果可能,您可以在方法本身中調(diào)用該函數(shù)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
如果該聲明由于某種原因不適用于您的程序,您可以使用簡單的檢查來檢查該函數(shù)是否已被調(diào)用。
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,計(jì)算就只會發(fā)生一次。

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

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

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超6個贊
有幾種方法可以做到這一點(diǎn)。
在類中存儲值
這可能是您可以做的最基本的事情:僅存儲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()
或者,您可以在構(gòu)造函數(shù)中計(jì)算_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”的技術(shù),該技術(shù)在 Python 中以functools.lru_cache
.?這基本上會記住帶有一組參數(shù)的函數(shù)調(diào)用結(jié)果,緩存并返回它而不是運(yùn)行該函數(shù)。
如果您不想讓人造成員弄亂您的班級,那么這很好。
from functools import lru_cache
class Problem:
? ? @lru_cache
? ? def _compute_start_end(self):
? ? ? ? ...
? ? ? ? return start, end
如果您使用 Python 3.9,您還可以使用functools.cache
,它是lru_cache
.
添加回答
舉報(bào)