美文网首页
函数执行结果缓存

函数执行结果缓存

作者: 不_一 | 来源:发表于2018-10-13 17:37 被阅读0次
    # -*- 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
    
    

    相关文章

      网友评论

          本文标题:函数执行结果缓存

          本文链接:https://www.haomeiwen.com/subject/fnooaftx.html