Denis Otkidach's 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 从foo.__dict__ 中删除了'bar',但该属性
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