Denis Otkidach 的 CachedAttribute是一种方法装饰器,它使属性变得惰性(计算一次,可多次访问)。为了使其也是只读的,我添加了一个__set__
方法。为了保留重新计算的能力(见下文),我添加了一个__delete__
方法:
class ReadOnlyCachedAttribute(object):
'''Computes attribute value and caches it in the instance.
Source: Python Cookbook
Author: Denis Otkidach https://stackoverflow.com/users/168352/denis-otkidach
This decorator allows you to create a property which can be computed once and
accessed many times. Sort of like memoization
'''
def __init__(self, method, name=None):
self.method = method
self.name = name or method.__name__
self.__doc__ = method.__doc__
def __get__(self, inst, cls):
if inst is None:
return self
elif self.name in inst.__dict__:
return inst.__dict__[self.name]
else:
result = self.method(inst)
inst.__dict__[self.name]=result
return result
def __set__(self, inst, value):
raise AttributeError("This property is read-only")
def __delete__(self,inst):
del inst.__dict__[self.name]
例如:
if __name__=='__main__':
class Foo(object):
@ReadOnlyCachedAttribute
# @read_only_lazyprop
def bar(self):
print 'Calculating self.bar'
return 42
foo=Foo()
print(foo.bar)
# Calculating self.bar
# 42
print(foo.bar)
# 42
try:
foo.bar=1
except AttributeError as err:
print(err)
# This property is read-only
del(foo.bar)
print(foo.bar)
# Calculating self.bar
# 42
关于CachedAttribute
(和 ReadOnlyCachedAttribute)的美妙之处之一是,如果您del foo.bar
, 那么下次您访问foo.bar
时,将重新计算该值。(这种魔法之所以成为可能,是因为从 中移除del foo.bar
但属性
仍保留在 中。)'bar'
foo.__dict__
bar
Foo.__dict__
如果您不需要或不希望这种能力重新计算,那么以下(基于Mike Boers 的 lazyprop)是创建只读惰性属性的更简单方法。
def read_only_lazyprop(fn):
attr_name = '_lazy_' + fn.__name__
@property
def _lazyprop(self):
if not hasattr(self, attr_name):
setattr(self, attr_name, fn(self))
return getattr(self, attr_name)
@_lazyprop.setter
def _lazyprop(self,value):
raise AttributeError("This property is read-only")
return _lazyprop