免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2102 | 回复: 0
打印 上一主题 下一主题

python 缓存函数调用的例子 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2012-11-21 16:05 |只看该作者 |倒序浏览
本帖最后由 wojiaohesen 于 2012-11-21 16:08 编辑

给大家分享一个缓存调用的例子。在python2.7中通过测试, 在其他的版本中, 请找到inpsect.getcallargs的代替实现即可, 可参看activepython.
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-

  3. class CacheCall(object):
  4.     def __init__(self, fn):
  5.         self.func = fn
  6.         self.cache = dict()
  7.         self.hits = 0
  8.         self.misses = 0

  9.     def __call__(self, *args, **kwargs):
  10.         import inspect
  11.         _key = inspect.getcallargs(self.func, *args, **kwargs)
  12.         key = tuple(sorted(_key.items()))
  13.         
  14.         result = self.cache.get(key, None)
  15.         if result:
  16.             self.hits += 1
  17.             return result
  18.         else:
  19.             self.misses += 1
  20.             result = self.func(*args, **kwargs)
  21.             self.cache[key] = result
  22.             return result

  23.     def __str__(self):
  24.         from pprint import pformat

  25.         return pformat(self.cache)


  26. @CacheCall
  27. def target(x, *y):
  28.     return x+len(y)

  29. if __name__ == "__main__":
  30.     print target(1,)
  31.     print target(1,)
  32.     print target(2,)
  33.     print target(3, (2,3,44))

  34.     print target
  35.    
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP