I want to do something like this, but I haven\'t had much success so far. I would like to make each attr a property that computes _lazy_eval only when accessed:
<
Descriptors (such as instances of the property
type) are only meaningful when they're held in the class object, not the instance object. So, you need to change the class, not the instance, and (in Python 2.6 or better) a class decorator is very handy for that purpose:
class Base(object):
def _lazy_eval(self, attr):
#Do complex stuff here
return attr
def lazyclass(cls):
for attr in cls._myattrs:
setattr(cls, attr, property(lambda self: self._lazy_eval(attr)))
return cls
@lazyclass
class Child(Base):
_myattrs = ['foo', 'bar']
If you're stuck with Python 2.5 or earlier, the decorator syntax doesn't apply to classes, but it's easy to get the same effect, just with less nifty syntax -- change the last 3 rows to:
class Child(Base):
_myattrs = ['foo', 'bar']
Child = lazyclass(Child)
which has the same semantics as the class decorator syntax.