计算一次函数并将结果存储在 python 中

Evaluate a function one time and store the result in python

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

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

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

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

@a
@b
def f():
   pass
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()