首页   注册   登录
V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python 学习手册
Python Cookbook
Python 基础教程
Python Sites
PyPI - Python Package Index
http://www.simple-is-better.com/
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
V2EX  ›  Python

class property 缓存

  •  
  •   fanhaipeng0403 · 50 天前 · 380 次点击
    这是一个创建于 50 天前的主题,其中的信息可能已经有所发展或是发生改变。
    from threading import RLock
    
    _missing = object()
    
    
    class locked_cached_property(object):
        """A decorator that converts a function into a lazy property.  The
        function wrapped is called the first time to retrieve the result
        and then that calculated result is used the next time you access
        the value.  Works like the one in Werkzeug but has a lock for
        thread safety.
        """
    
        def __init__(self, func, name=None, doc=None):
            self.__name__ = name or func.__name__
            self.__module__ = func.__module__
            self.__doc__ = doc or func.__doc__
            self.func = func
            self.lock = RLock()
    
        def __get__(self, obj, type=None):
            if obj is None:
                return self
            with self.lock:
                value = obj.__dict__.get(self.__name__, _missing)
                if value is _missing:
                    value = self.func(obj)
                    obj.__dict__[self.__name__] = value
                return value
                
    
    In [27]: class B:
        ...:     @locked_cached_property
        ...:     def foo(self):
        ...:         import time
        ...:
        ...:         print('processing....')
        ...:         time.sleep(10)
        ...:         return 'b'
        ...:
        ...:
    
    In [28]: b = B()
    
    In [29]: b.foo
    processing....
    Out[29]: 'b'
    
    In [30]: b.foo
    Out[30]: 'b'
    
    In [31]:
    
    目前尚无回复
    关于   ·   FAQ   ·   API   ·   我们的愿景   ·   广告投放   ·   感谢   ·   实用小工具   ·   3798 人在线   最高记录 4346   ·  
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.3 · 20ms · UTC 07:06 · PVG 15:06 · LAX 23:06 · JFK 02:06
    ♥ Do have faith in what you're doing.
    沪ICP备16043287号-1