栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python-延迟加载类属性

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/652452.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号