3 回答

TA貢獻(xiàn)2019條經(jīng)驗 獲得超9個贊
對于各種強(qiáng)大的工具,我都使用bolton。
作為該庫的一部分,您具有cached屬性:
from boltons.cacheutils import cachedproperty
class Foo(object):
def __init__(self):
self.value = 4
@cachedproperty
def cached_prop(self):
self.value += 1
return self.value
f = Foo()
print(f.value) # initial value
print(f.cached_prop) # cached property is calculated
f.value = 1
print(f.cached_prop) # same value for the cached property - it isn't calculated again
print(f.value) # the backing value is different (it's essentially unrelated value)

TA貢獻(xiàn)1847條經(jīng)驗 獲得超7個贊
這是惰性屬性裝飾器的示例實現(xiàn):
import functools
def lazyprop(fn):
attr_name = '_lazy_' + fn.__name__
@property
@functools.wraps(fn)
def _lazyprop(self):
if not hasattr(self, attr_name):
setattr(self, attr_name, fn(self))
return getattr(self, attr_name)
return _lazyprop
class Test(object):
@lazyprop
def a(self):
print 'generating "a"'
return range(5)
互動環(huán)節(jié):
>>> t = Test()
>>> t.__dict__
{}
>>> t.a
generating "a"
[0, 1, 2, 3, 4]
>>> t.__dict__
{'_lazy_a': [0, 1, 2, 3, 4]}
>>> t.a
[0, 1, 2, 3, 4]

TA貢獻(xiàn)2051條經(jīng)驗 獲得超10個贊
我為自己編寫了此代碼...用于真正的一次性計算的惰性屬性。我喜歡它,因為它避免在對象上粘貼額外的屬性,并且一旦激活就不會浪費(fèi)時間檢查屬性是否存在,等等:
import functools
class lazy_property(object):
'''
meant to be used for lazy evaluation of an object attribute.
property should represent non-mutable data, as it replaces itself.
'''
def __init__(self, fget):
self.fget = fget
# copy the getter function's docstring and other attributes
functools.update_wrapper(self, fget)
def __get__(self, obj, cls):
if obj is None:
return self
value = self.fget(obj)
setattr(obj, self.fget.__name__, value)
return value
class Test(object):
@lazy_property
def results(self):
calcs = 1 # Do a lot of calculation here
return calcs
注意:lazy_property該類是一個非數(shù)據(jù)描述符,這意味著它是只讀的。添加__set__方法會阻止其正常工作。
添加回答
舉報