Vincent Gulinao wrote: > Sorry about that. I want something like: > > class foo: > > def __init__(self): > > self.attr1 = None > > > def get_attr1(self): > > if not self.attr1: > > attr1 = <get value from DB, very expensive query> > > self.attr1 = attr1 > > return self.attr1 > > > such that: > > foo_instance = foo() > > then: > > foo_instance.get_attr1() > > and > > foo_instance.attr1 > > gets the same value. > > > Such that you get to derive attr1 only as needed and just once, both > outside and within foo class.
I would do it like this: class Foo(object): def __getattr__(self, attr): if not <attr is something you can get from the database>: raise AttributeError( "'%s' object has no attribute '%s'" % (self.__class__.__name__, attr)) value = <get attr from database> setattr(self, attr, value) return value You don't need to init attr1 and you don't need get_attr1(). The first time you try to read foo.attr1, there will be no attr1 attribute so __getattr(self, 'attr1') will be called. You read the value from the database and save it as an ordinary attribute; future accesses will read the ordinary attribute and skip the __getattr__() call. Kent _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor