class.__getattr__ behavior: feature or bug?

Tim Peters tim_one at email.msn.com
Fri Jan 14 16:36:32 EST 2000


[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.

To fix that, don't do this <wink>, define S.__repr__, or capture the name
"__repr__" in your __getattr__ and return something sensible for it.

Note that __getattr__/__setattr__ are "advanced" features -- meaning mostly
that they're low-level hooks bristling with subtleties.

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






More information about the Python-list mailing list