0

計算に時間がかかる静的メソッドを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
4

2 に答える 2

0
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()
于 2015-01-26T09:21:38.280 に答える
0

あなたがやりたいことは と呼ばれていると思いますmemoizing。デコレータでそれを行うにはいくつかの方法があります。そのうちの 1 つはfunctools(Python 3)を使用するか、ハッシュ可能な型 (Python 2 の場合も同様) のみを扱う場合はいくつかの短い手書きコードを使用します。

1 つのメソッドに対して複数のデコレータに注釈を付けることができます。

@a
@b
def f():
   pass
于 2015-01-26T09:14:59.023 に答える