class.__getattr__ behavior: feature or bug?

Huayin Wang wang at rjka.com
Fri Jan 14 17:24:22 EST 2000


[Tim Peters]
> [Huayin Wang]
> > >>> class S:
> > ...    def __getattr__(self, name):
> > ...       if name == 'c':
> > ...          self.a = self.a + 1
> > ...          return self.a
> > ...       else: return None
> > ...
> > >>> s=S()
> > >>> s
> > Traceback (innermost last):
> >   File "<stdin>", line 1, in ?
> > TypeError: call of non-function (type None)
> > >>>

> Feature.  Try sticking "print name" in __getattr__ to see what's happening.
> Putting "s" on a line by itself implicitly asks Python to invoke repr(s) (to
> build an output string), so Python tries to look up the special method
> s.__repr__.  Your __getattr__ returns None, and Python complains that None
> isn't a sensible __repr__ method.

I used to think that I know what's a bug and what's a feature, now I am 
confused.  I do not understand why I would want to use __getattr__ special
method to control/define other special methods like '__repr__' when I can
just define it if I want to.

I know I got a mouthful with the last sentence :)

By the way, does any of you tested you code/idea ;) and
is infinite __getattr__ loop a bug?

> your-next-post-will-be-wondering-whether-an-infinite-
>    __getattr__-loop-is-a-bug<0.5-wink>-ly y'rs  - tim

never mind :)




More information about the Python-list mailing list