当前的答案存在一些问题。具有属性的解决方案要求您指定其他类属性,并且在每次查找时都要检查该属性。该解决方案
__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
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)