Newbie again: computing attributes on the fly

Olaf Delgado delgado at Mathematik.Uni-Bielefeld.DE
Wed Jun 16 10:07:28 EDT 1999


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

>>> y = x()
>>> y.lost()
0
>>> y.a_life()
1

Here, the lambda is pointless somehow, but hints to a potential desire to
add parameter support in the future (which I think I don't need, but who
knows?).

Question(s):
1) Is this 'good', or at least 'okay' style?
2) Any immediate suggestions for improvement?
3) Has anyone ever bothered to implement a more elegant or more complete
   approach, which might, for example, include such things as parameters,
   adding memorization to existing classes, you name it?

Thanks for reading,
Olaf

-- 
   ////         Olaf Delgado Friedrichs, Uni Bielefeld, Mathematik
   Olaf         Postfach 100131                  (room:  V4-109)
   `='          D-33501 Bielefeld, Germany       (phone: +49 521 106-4765)
                           http://www.mathematik.uni-bielefeld.de/~delgado





More information about the Python-list mailing list