对函数求值一次并将结果存储在python中

2024-09-29 06:27:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我用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

Tags: 代码示例footimedef时间someresult
2条回答
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()

我想你要做的就是memoizing。 有几种方法可以使用decorator,其中一种是使用^{}(python3)或一些short handwritten code(如果您只关心可哈希类型(也适用于python2))。你知道吗

可以为一个方法注释多个装饰器。你知道吗

@a
@b
def f():
   pass

相关问题 更多 >