- 论坛徽章:
- 0
|
本帖最后由 wojiaohesen 于 2012-11-21 16:08 编辑
给大家分享一个缓存调用的例子。在python2.7中通过测试, 在其他的版本中, 请找到inpsect.getcallargs的代替实现即可, 可参看activepython.- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- class CacheCall(object):
- def __init__(self, fn):
- self.func = fn
- self.cache = dict()
- self.hits = 0
- self.misses = 0
- def __call__(self, *args, **kwargs):
- import inspect
- _key = inspect.getcallargs(self.func, *args, **kwargs)
- key = tuple(sorted(_key.items()))
-
- result = self.cache.get(key, None)
- if result:
- self.hits += 1
- return result
- else:
- self.misses += 1
- result = self.func(*args, **kwargs)
- self.cache[key] = result
- return result
- def __str__(self):
- from pprint import pformat
- return pformat(self.cache)
- @CacheCall
- def target(x, *y):
- return x+len(y)
- if __name__ == "__main__":
- print target(1,)
- print target(1,)
- print target(2,)
- print target(3, (2,3,44))
- print target
-
复制代码 |
|