Perl vs. Python question...
Joshua Judson Rosen
rozzin at geekspace.com
Tue Jul 14 15:32:40 EDT 2009
Lloyd Kvam <python at venix.com> writes:
>
> On Mon, 2009-07-13 at 22:59 -0400, Paul Lussier wrote:
> > Lloyd Kvam <python at 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__.
That's not true; it *will*, however, trigger a call to __settattr__,
if it exists; that's what you're thinking of :)
cf. http://docs.python.org/reference/datamodel.html#object.__setattr__
__getattr__, however, is free to just do `self.foo = ...'.
--
Don't be afraid to ask (Lf.((Lx.xx) (Lr.f(rr)))).
More information about the gnhlug-discuss
mailing list