2013-06-18 18 views
1

我是python的新手,我無法在線找到答案。 可以說我有,做一些計算,並返回一個字符串記憶一個使用實例屬性的函數

def output(self) 
    a=self.some_long computation1() 
    b=self.some_long computation2() 
    c=self.some_attribute 
    some_computatuion_inside 
    return output_string 

我使用這個功能,在一些地方,想memoize的,但因爲它沒有參數,取決於實例屬性的方法,它可以改變電話間,我不知道如何繼續,

我意識到我可以寫我自己的memoization功能,將檢查如果這些屬性改變,但這似乎是不正確的,因爲這將是特定於此功能只有 和我希望將來也可以爲其他功能做同樣的工作

+1

儘量考慮''some_long_computationX''記憶化 – fogbit

回答

1

一種方法是拉出變量(假定他們是可哈希),並使其成爲一個static method

@staticmethod 
def output_static(a, b, c) 
    some_computatuion_inside 
    return output_string 

再從類中調用它爲:

self.output_static(a=self.some_long_computation1() 
        b=self.some_long_computation2() 
        c=self.some_attribute) 

你也可以使用techinque來記憶some_long_computation1some_long_computation1

如果你想你可以寫一箇中介輔助函數這將簡單的調用(memomized)靜態方法:

def output(self): 
    return self.output_static(a=self.some_long_computation1() 
           b=self.some_long_computation2() 
           c=self.some_attribute) 
1

裝飾可以計算基於任何爭論的關鍵。任何實例方法有一個參數,即self,這是很容易使用,以獲得方法memoize的裝飾:

CACHE = {} 

def memoize(*attributes): 
    def decorator(meth): 
     def wrapper(self): 
      key = tuple(getattr(self, attr) for attr in attributes) 
      try: 
       result = CACHE[key] 
      except KeyError: 
       result = CACHE[key] = meth(self) 
      return result 
     return wrapper 
    return decorator 

用法:

class Factorial(object): 
    def __init__(self, n): 
     self.n = n 
    @memoize('n') 
    def compute(self): 
     if self.n in (0,1): return self.n 
     else: 
      return Factorial(self.n-1).compute() + Factorial(self.n-2).compute() 


f = Factorial(100) 

f.compute() 
Out[4]: 354224848179261915075L 
相關問題