python resettable实例方法备忘录装饰器

python resettable实例方法备忘录装饰器,第1张

python resettable实例方法备忘录装饰

我没有尝试弄清实现的机制,而是

memoized
从PythonDecoratorLibrary获取了decorator类,并将其修改为add
reset
。结果如下:我使用的技巧是
reset
在装饰后的函数本身中添加一个callable属性。

    class memoized2(object):       """Decorator that caches a function's return value each time it is called.       If called later with the same arguments, the cached value is returned, and       not re-evaluated.       """       def __init__(self, func):          self.func = func          self.cache = {}       def __call__(self, *args):          try:  return self.cache[args]          except KeyError:  value = self.func(*args)  self.cache[args] = value  return value          except TypeError:  # uncachable -- for instance, passing a list as an argument.  # Better to not cache than to blow up entirely.  return self.func(*args)       def __repr__(self):          """Return the function's docstring."""          return self.func.__doc__       def __get__(self, obj, objtype):          """Support instance methods."""          fn = functools.partial(self.__call__, obj)          fn.reset = self._reset          return fn       def _reset(self):          self.cache = {}    class my_class:        @memoized2        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)


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5655486.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存