python可重置实例方法备忘录d

2024-06-16 10:36:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图为一个类的实例方法构建一个decorator,该类将记录结果。(这在以前已经做了一百万次了)但是,我希望能够在任何时候重置已记录的缓存(比如,如果实例状态中的某些内容发生更改,这可能会更改与参数无关的方法的结果)。因此,我尝试将decorator构建为类而不是函数,以便可以作为类成员访问缓存。这引导我沿着学习描述符的道路前进,特别是__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__时,我都会得到一个新的memoided类实例,它会丢失包含实际数据的缓存。我一直在努力工作,但进展不大。

有没有一个完全独立的方法来解决我完全忽略的问题?欢迎并感谢所有的建议。谢谢。


Tags: 方法selfcachenewgetreturntimemy