One-Shot Property?
Scott David Daniels
Scott.Daniels at Acm.Org
Tue Jan 18 15:05:52 EST 2005
Leif K-Brooks wrote:
>
> class CachingProperty(object):
> def __init__(self, attr_name, calculate_function):
> self._name = attr_name
> self._calculate = calculate_function
> def __get__(self, obj, type=None):
> if obj is None:
> return self
> else:
> value = self._calculate(obj)
> setattr(obj, self._name, value)
> return value
>
> And example code:
> >>> class Foo(object):
> ... def calculate_value(self):
> ... print 'Calculating...'
> ... return 42
> ... foo = CachingProperty('foo', calculate_value)
> ...
> >>> bar = Foo()
> >>> bar.__dict__
> {}
> >>> bar.foo
> Calculating...
> 42
> >>> bar.foo # Notice that the print statement doesn't run this time
> 42
> >>> bar.__dict__
> {'foo': 42}
To build on this for Python 2.4:
class Caches(object):
def __init__(self, calculate_function):
self._calculate = calculate_function
def __get__(self, obj, _=None):
if obj is None:
return self
value = self._calculate(obj)
setattr(obj, self._calculate.func_name, value)
return value
class Foo(object):
@Caches
def foo(self):
print 'Calculating...'
return 42
--Scott David Daniels
Scott.Daniels at Acm.Org
More information about the Python-list
mailing list