Denis Otkidach 的 CachedAttribute http://code.activestate.com/recipes/276643-caching-and-aliasing-with-descriptors/是一个方法装饰器,它使属性变得惰性(计算一次,可访问多次)。为了使其只读,我添加了一个__set__
方法。为了保留重新计算的能力(见下文),我添加了一个__delete__
method:
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'
from foo.__dict__
但财产bar
仍留在Foo.__dict__
.)
如果你不需要或者不希望这种重新计算的能力,
然后是以下内容(基于迈克·波尔斯 (Mike Boers) 的懒惰道具 https://stackoverflow.com/questions/3012421/python-lazy-property-decorator/3013910#3013910) 是创建只读惰性属性的更简单方法。
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