Newbie again: computing attributes on the fly

Olaf Delgado delgado at Mathematik.Uni-Bielefeld.DE
Wed Jun 16 19:58:44 CEST 1999


Hi and thanks for answering!

On Wed, 16 Jun 1999, Gordon McMillan wrote:

> Olaf Delgado writes:
> > 
> > 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")
> > [...]


> You're making things too complicated. __getattr__ is only called if 
> the attribute is not found. So something like this will suffice:
> [...]
> If you want to generalize that, I'd see if we have an attribute 
> "calc_%s" % nm and use that method (vs the inline computation).

Yes, I definitely want to generalize that. The problem is that that method
may be defined in a superclass, so "self.__dict__" won't find it. AFAIK
(which may be not be very far), I have to use "hasattr" and/or "getattr",
which in turn will call "__getattr__".

Recursively yours,
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