2011-12-23 17 views
0

這個問題是關於python resettable instance method memoization decorator的答案的後續。事實上,我會寫這個作爲對這個答案的評論,但我沒有(但是,我希望)有足夠的聲望。python resettable memoization decorator(對於某個實例)

在這個答案中,@aix給出了一個使用裝飾器重置memoized函數的好方法。

這個答案的「問題」是針對某個裝飾方法調用reset重置所有實例的緩存。使用@aix定義相同的類的實例應該清楚:

c = my_class() 
print c.my_func(55) 
# This time the function is computed and stored in cache 
print c.my_func(55) 
# This second call is cached... no computation needed 
d = my_class() 
d.my_func.reset() 
print c.my_func(55) 
# This third call is also computed, since the cache has been cleared 

我認爲d.my_func.reset()應該只清除緩存的d.my_func預先計算的值,而不是爲my_class所有其他實例。

我有一個不完全說服的半解決方案,但我想有人可以改進。

我已經修改了reset()方法,並引入了參數instance

def _reset(self,instance): 
    for cached in self.cache.keys(): 
     if cached[0] == instance: 
      del self.cache[cached] 

現在,如果我做的:

c = my_class() 
print c.my_func(55) 
# This time the function is computed and stored in cache 
print c.my_func(55) 
# This second call is cached 
d = my_class() 
d.my_func.reset(d) 
print c.my_func(55) 
# Now this third call is cached 

但是,方法來調用復位方法:d.my_func.reset(d)看來(至少)醜陋,但我一直沒能找到更好的解決方案...有沒有人有一些想法?

謝謝!

編輯

爲了記錄:強似實例作爲一個參數,你可以得到相同的行爲改變裝飾的__get__方法。

__get__(self, obj, objtype)方法添加self.original_self = obj並在_reset方法替代if cached[0] == instanceif cached[0] == self.original_self。這解決了問題!

回答

0

您可以使用該方法的__self__屬性(在本例中爲self.__self__)查找綁定的類實例(而不必通過實例)。

+0

感謝您的回答,但由於該方法是裝飾,如果在我的代碼中,我用'if cached [0] == self .__ self__'替換'if cached [0] == instance''我得到''memoized2'對象沒有屬性'__self __'' – 2011-12-23 19:21:06

+0

感謝您花時間回覆我認爲我有一個合理的解決方案(請參閱編輯問題)。 – 2011-12-23 20:13:04