On Mon, 2009-07-13 at 22:59 -0400, Paul Lussier wrote: > Lloyd Kvam <pyt...@venix.com> writes: > > > You've already gotten two useful responses. I'd just like to add that > > typically, the object attributes are referenced directly: > > rect.length * rect.width > > Lloyd, thanks. But what if the attribute isn't set yet? If I have > self.foo, and self.foo hasn't yet been set, I want it to go and get set, > then return the correct value.
If the initial set value is a simple constant, make it a class attribute with the default value. The object can override the attribute with a different value when that value is determined. > > I get the impression the __getattr__() method helps here, If the value will be computed on demand, __getattr__ is one way to go. def __getattr__(self, attr): if attr == 'foo': return self.compute_foo() elif .... else: raise AttributeError( attr + ' is invalid name') This is the 'traditional' approach. __getattr__ is *only* called when an attribute is not found. If you wanted to save the computed value, so that __getattr__ was no longer used: self.__dict__['foo'] = self.compute_foo() return self.foo The simplistic self.foo = self.compute_foo() will trigger a call to __getattr__, so you can't use that within __getattr__. The new-style python classes allow for cleaner dispatching of your attribute computations using properties, but for a small number of names, __getattr__ will do just fine. If there is no setter method and foo is always computed, your class could be coded: foo = property( compute_foo) > I just don't > quite get it yet. HTH > > -- > Thanks, > Paul -- Lloyd Kvam Venix Corp DLSLUG/GNHLUG library http://dlslug.org/library.html http://www.librarything.com/catalog/dlslug http://www.librarything.com/rsshtml/recent/dlslug http://www.librarything.com/rss/recent/dlslug _______________________________________________ gnhlug-discuss mailing list gnhlug-discuss@mail.gnhlug.org http://mail.gnhlug.org/mailman/listinfo/gnhlug-discuss/