函数执行结果缓存

# -*- coding: utf-8 -*-
from time import time


class cached_property(object):
    def __init__(self, ttl=None):
        ttl_or_func = ttl
        self.ttl = None
        if callable(ttl_or_func):
            self.prepare_func(ttl_or_func)
        else:
            self.ttl = ttl_or_func

    def prepare_func(self, func, doc=None):
        """Prepare to cache object method."""
        self.func = func
        self.__doc__ = doc or func.__doc__
        self.__name__ = func.__name__
        self.__module__ = func.__module__

    def __call__(self, func, doc=None):
        self.prepare_func(func, doc)
        return self

    def __get__(self, obj, cls):
        if obj is None:
            return self
        now = time()
        try:
            value, last_update = obj._cache[self.__name__]
            if self.ttl and self.ttl > 0 and now - last_update > self.ttl:
                raise AttributeError
        except (KeyError, AttributeError):
            value = self.func(obj)
            try:
                cache = obj._cache
            except AttributeError:
                cache = obj._cache = {}
            cache[self.__name__] = (value, now)
        return value


class Foo(object):
    def __init__(self):
        pass

    @cached_property
    def pp(self):
        return 'hello'

    def world(self):
        return 'world'

    PP = cached_property(world)

    print(PP)
    print(world)


#
# print(Foo())
# print(Foo().pp)


print(Foo().PP)  # 传入self

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容