bringtree / question_embedding

这个仓库的issues里记录了许多奇奇怪怪的东西(100+)。
1 stars 1 forks source link

实用的装饰器 收集 #138

Open bringtree opened 6 years ago

bringtree commented 6 years ago

cache 保存函数结果

class Cache:
    def __init__(self, func):
        self.func = func
        self.data = {}

    def __call__(self, *args, **kwargs):
        func = self.func
        data = self.data
        key = f'{func.__name__}-{str(args)}-{str(kwargs)}'

        if key in data:
            result = data.get(key)

        else:
            result = func(*args, **kwargs)
            data[key] = result

        return result