Newbie again: computing attributes on the fly
Clarence Gardner
clarence at silcom.com
Wed Jun 16 11:19:05 EDT 1999
Olaf Delgado (delgado at Mathematik.Uni-Bielefeld.DE) wrote:
: Hi everybody,
:
: here's another couple of questions to the enlightened ones. I'd like to
: compute certain properties of a class instance only once and store it for
: future use. I'd like to do those computations on demand only, because some
: might be really, really expensive. My first try looks like this:
:
: class x:
: def __getattr__(self, attr):
: import string
: if string.find(attr, "get_") != 0:
: val = ( lambda x = getattr(self, "get_"+attr)(): x )
: self.__dict__[attr] = val
: return val
: else:
: raise AttributeError("no such attribute")
:
: def get_lost(self):
: return 0 # really, really expensive :)
:
: def get_a_life(self):
: return 1
On occasion I've done things like this (not necessarily for cost reasons,
but I just might want to do something different the first time). What
I've done is:
class x:
def dosomething(self, arg):
initial blah, blah, blah
self.dosomething = self._dosomething2
def _dosomething2(self, arg):
second_and_subsequent blah, blah, blah
--
-=-=-=-=-=-=-=-=
Clarence Gardner
AvTel Communications
Software Products and Services Division
clarence at avtel.com
More information about the Python-list
mailing list