您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python-延迟加载类属性

Python-延迟加载类属性

当前的答案存在一些问题。具有属性解决方案要求您指定其他类属性,并且在每次查找时都要检查该属性。该解决方__getattr__的问题在于,它会隐藏该属性,直到首次访问。这不利于自省,并且__dir__不便解决

比两个建议的解决方案更好的解决方案是直接使用描述符。werkzeug库已经有一个解决方werkzeug.utils.cached_property。它具有一个简单的实现,因此您可以直接使用它而无需将Werkzeug作为依赖项:

_missing = object()

class 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::

        class Foo(object):

            @cached_property
            def foo(self):
                # calculate something important here
                return 42

    The class has to have a `__dict__` in order for this property to
    work.
    """

    # implementation detail: this property is implemented as non-data
    # descriptor.  non-data descriptors are only invoked if there is
    # no entry with the same name in the instance's __dict__.
    # this allows us to completely get rid of the access function call
    # overhead.  If one choses to invoke __get__ by hand the property
    # will still work as expected because the lookup logic is replicated
    # in __get__ for manual invocation.

    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

    def __get__(self, obj, type=None):
        if obj is None:
            return self
        value = obj.__dict__.get(self.__name__, _missing)
        if value is _missing:
            value = self.func(obj)
            obj.__dict__[self.__name__] = value
        return value
python 2022/1/1 18:46:18 有312人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶