【问题标题】:Evaluate a function one time and store the result in python一次评估一个函数并将结果存储在python中
【发布时间】:2015-01-26 09:08:17
【问题描述】:

我在 python 中编写了一个静态方法,它需要时间来计算,但我希望它只计算一次,然后返回计算值。 我该怎么办 ? 这是一个示例代码:

class Foo:
    @staticmethod
    def compute_result():
         #some time taking process 

Foo.compute_result() # this may take some time to compute but store results
Foo.compute_result() # this method call just return the computed result

【问题讨论】:

    标签: python static-methods evaluation-strategy


    【解决方案1】:
    def evaluate_result():
        print 'evaluate_result'
        return 1
    
    class Foo:
        @staticmethod
        def compute_result():
            if not hasattr(Foo, '__compute_result'):
                Foo.__compute_result = evaluate_result()
            return Foo.__compute_result 
    
    Foo.compute_result()
    Foo.compute_result()
    

    【讨论】:

      【解决方案2】:

      我想你想做的事情叫做memoizing。 有几种使用装饰器的方法,其中一种是使用functools(Python 3)或一些short handwritten code,如果您只关心可散列类型(也适用于 Python 2)。

      您可以为一种方法注释多个装饰器。

      @a
      @b
      def f():
         pass
      

      【讨论】:

        猜你喜欢
        • 2019-05-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-03
        • 1970-01-01
        • 2016-07-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多