繁体   English   中英

将函数的结果复制为类变量或多次调用它

[英]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

我以为只调用一次函数而不是多次调用会更快,但是由于deltasthetasepsilons函数都很小,因此我不确定这很重要。

现在我想知道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的最新版本对此有一个很好的解决方案: functoolslru_cache 这个装饰器使您可以让Python记住对特定参数组合的函数调用的结果(这假设如果使用相同的参数,则所述函数的结果将相同)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM