python 基础——实现一个带缓存功能的函数

from functools import wraps

def cache(func):
    data = {}
    @wraps(func)
    def wrapper(*args):
        if args in data:
            print "in cache"
            return data[args]
        else:
            print "not in cache"
            res = func(*args)
            data[args] = res
            return res
    return wrapper

@cache
def post_data(args):
    return args

post_data(123)    # not in cache
post_data(123)    # in cache
post_data(1235)    # not in cache

 

posted @ 2016-08-26 16:20  弋痕夕的残影  阅读(1055)  评论(0编辑  收藏  举报