函數(shù)執(zhí)行結(jié)果緩存

# -*- 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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容