Python 将函数的结果作为类变量复制或多次调用
我正在编写一个类,它多次使用几个非成员函数(所有函数都返回列表)的结果 我想知道处理这件事的标准方法是什么——我最初的想法是按照以下思路写一些东西:Python 将函数的结果作为类变量复制或多次调用,python,class,Python,Class,我正在编写一个类,它多次使用几个非成员函数(所有函数都返回列表)的结果 我想知道处理这件事的标准方法是什么——我最初的想法是按照以下思路写一些东西: class Y_and_Z_matrices(object): def __init__(self, roots_p, roots): self.deltas = deltas(roots) self.deltas_p = deltas(roots_p) self.thetas = theta
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
我认为只调用一次而不是多次的函数会更快,但由于增量
,θ
和ε
函数都非常小,我不确定这是否重要
现在我想知道python在这种情况下是如何工作的,这比在我将使用的每个函数中调用delta
函数好吗?保存列表根
并引用它们是否比将它们传递给许多函数更好
即,重写上述内容的(dis)优点是什么:
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
我想用第二种方法编写这个类,但唯一的原因是我喜欢参数列表尽可能小的函数的外观,而且我不喜欢我的\uuuuu init\uuu
函数看起来如此笨拙
总结问题:
客观上,将函数的返回保存为成员变量比在多个成员函数中调用函数更好还是更差
保存参数(在整个类中都是相同的)或使用所需参数调用函数客观上是更好还是更差
或
只是在某个地方(如果是的话,在哪里)有一个折衷方案吗?Python3的最新版本有一个很好的解决方案:
functools
'。此修饰符允许Python记住特定参数组合的函数调用结果(假设使用相同的参数,则所述函数的结果将是相同的)。对我来说似乎很好:第一次可以避免计算开销,特别是在计算“希腊字母”时这是一个漫长的过程。但是为什么不在init中将根
、根和其他变量分配给self
?这避免了方法调用中的额外参数;您可以定义一个私有方法来设置delta等,并从\uuuu init\uuuuu
调用它,如果您发现\uuuuu init\uuuuu
太难处理(我认为不是),这是一种折衷。您必须在初始化器上花费额外的精力,并编写额外的代码行;作为交换,你会得到一个潜在的速度提升。通常的建议是,在试图解决性能问题之前,不要担心性能问题。多亏了你们两位——我本应该写得更清楚的主要一点是,我不确定这是否会更快,或者我是否对代码的工作方式做出了错误的假设。