結果をメモするクラスのインスタンス メソッドのデコレータを構築しようとしています。(これは以前に 100 万回行われています) ただし、メモ化されたキャッシュをいつでもリセットできるオプションが欲しいです (たとえば、インスタンスの状態が変化した場合、何もないメソッドの結果が変わる可能性があります)。その引数を処理する)。そこで、クラス メンバーとしてキャッシュにアクセスできるように、関数ではなくクラスとしてデコレータを構築しようとしました。これにより、記述子、特にメソッドについて学習する道をたどりましたが、__get__
実際に行き詰まっているところです。私のコードは次のようになります。
import time
class memoized(object):
def __init__(self, func):
self.func = func
self.cache = {}
def __call__(self, *args, **kwargs):
key = (self.func, args, frozenset(kwargs.iteritems()))
try:
return self.cache[key]
except KeyError:
self.cache[key] = self.func(*args, **kwargs)
return self.cache[key]
except TypeError:
# uncacheable, so just return calculated value without caching
return self.func(*args, **kwargs)
# self == instance of memoized
# obj == instance of my_class
# objtype == class object of __main__.my_class
def __get__(self, obj, objtype=None):
"""Support instance methods"""
if obj is None:
return self
# new_func is the bound method my_func of my_class instance
new_func = self.func.__get__(obj, objtype)
# instantiates a brand new class...this is not helping us, because it's a
# new class each time, which starts with a fresh cache
return self.__class__(new_func)
# new method that will allow me to reset the memoized cache
def reset(self):
print "IN RESET"
self.cache = {}
class my_class:
@memoized
def my_func(self, val):
print "in my_func"
time.sleep(2)
return val
c = my_class()
print "should take time"
print c.my_func(55)
print
print "should be instant"
print c.my_func(55)
print
c.my_func.reset()
print "should take time"
print c.my_func(55)
これは明確ですか、および/または可能ですか? が呼び出されるたび__get__
に、メモ化されたクラスの新しいインスタンスを取得します。これにより、実際のデータを含むキャッシュが失われます。私は と懸命に取り組んできましたが__get__
、あまり進歩していません。
私が完全に見逃しているこの問題に対する完全に別のアプローチはありますか? そして、すべてのアドバイス/提案は大歓迎です。ありがとう。