栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/653381.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号