亚洲av成人无遮挡网站在线观看,少妇性bbb搡bbb爽爽爽,亚洲av日韩精品久久久久久,兔费看少妇性l交大片免费,无码少妇一区二区三区

Chinaunix

標題: python 緩存函數(shù)調用的例子 [打印本頁]

作者: wojiaohesen    時間: 2012-11-21 16:05
標題: python 緩存函數(shù)調用的例子
本帖最后由 wojiaohesen 于 2012-11-21 16:08 編輯

給大家分享一個緩存調用的例子。在python2.7中通過測試, 在其他的版本中, 請找到inpsect.getcallargs的代替實現(xiàn)即可, 可參看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.    
復制代碼





歡迎光臨 Chinaunix (http://www.72891.cn/) Powered by Discuz! X3.2