![](/img/trans.png)
[英]Python giving same result when I call a function multiple times, despite random component
[英]Copy the result of a function as a class variable or call it multiple times Python
我正在編寫一個使用多次非成員函數(均返回列表)的結果的類。
我想知道處理這個問題的標准方式是什么-我最初的想法是寫一些類似的東西:
class Y_and_Z_matrices(object):
def __init__(self, roots_p, roots):
self.deltas = deltas(roots)
self.deltas_p = deltas(roots_p)
self.thetas = thetas(roots)
self.thetas_p = thetas_p(roots_p)
self.epsilons = epsilons(roots)
self.epsilons_p = epsilons(roots_p)
def _func_a (self, roots_p, roots, param):
#refers to the member variables
def _func_b (self, roots_p, roots, param):
#refers to the member variables
def Ymatrix(self, roots_p, roots):
#refers to the member variables
def Zmatrix(self, roots_p, roots):
#refers to member variables
我以為只調用一次函數而不是多次調用會更快,但是由於deltas
, thetas
和epsilons
函數都很小,因此我不確定這很重要。
現在我想知道python在這種情況下如何工作,這比在我將要使用它們的每個函數中調用deltas
函數更好嗎? 保存列表roots
並引用它們而不是將它們傳遞給許多功能會更好嗎?
即重寫上述內容有哪些(缺點):
class Y_and_Z_matrices(object):
def __init__ (self, roots_p, roots, param):
self.roots_p = roots_p
self.roots = roots
self.param = param
def _func_a (self):
#uses 'roots_p', 'roots', and 'param' member variables
#passes 'roots' and 'roots_p' to 'deltas', 'epsilons' and 'thetas' when needed
def _func_b (self):
#uses 'roots_p', 'roots', and 'param' member variables
#passes 'roots' and 'roots_p' to 'deltas', 'epsilons' and 'thetas' when needed
def Ymatrix(self):
#uses 'roots_p', and 'roots' member variables
#passes 'roots' and 'roots_p' to 'deltas', 'epsilons' and 'thetas' when needed
def Zmatrix(self):
#uses 'roots_p', and 'roots' member variables
#passes 'roots' and 'roots_p' to 'deltas', 'epsilons' and 'thetas' when needed
我想用第二種方式編寫類,但是唯一的原因是因為我喜歡帶有盡可能小的參數列表的函數外觀,而且我不喜歡__init__
函數看起來笨拙。
總結問題:
將函數的返回結果保存為成員變量,而不是在多個成員函數中調用函數,客觀上是好是壞?
保存參數(在整個類中將是相同的)還是調用具有所需參數的函數,客觀上是好是壞?
要么
僅僅是在某處(如果有,在哪里)之間進行權衡?
Python3的最新版本對此有一個很好的解決方案: functools
的lru_cache
。 這個裝飾器使您可以讓Python記住對特定參數組合的函數調用的結果(這假設如果使用相同的參數,則所述函數的結果將相同)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.