Is this an Intended behaviour of __getattr__?
Jeff Shannon
jeff at ccvcorp.com
Thu Aug 2 13:19:15 EDT 2001
Grace wrote:
> I'm a bit confused with this:
>
> class Node:
> def __init__(self):
> self._next=None
> def __getattr__(self,attr):
> if attr=='next':
> if self._next is not None:
> return self._next
> else:
> self._next=Node()
> return self._next
> print attr,"was called..."
> error=3/0 #supposed to raise exception
> raise AttributeError
>
> if __name__=='__main__':
> f=Node()
> links=[f.next,f.next,f.next.next,f.next.next]
> for each in links:
> print each
> print f.errorPlz
>
> And this yields exactly,
>
[snipping output]
>
> Why did it suck up all ZeroDivisionErrors while outputting the "was
> called..." messages? Special case with magic methods? Is this an intended
> behaviour? Then what is the exact process/mechanism?
>
> Thanks in advance.
IIRC, when searching for attributes, __getattr__() is only called when the
attribute is not found in any of the usual places. It's a last-ditch save,
rather than a total redefine, in this sense. Since the interpreter is able
to find attributes for __str__(), et al, it uses those and does not pass
through __getattr__().
Of course, I could be totally wrong. :)
Jeff Shannon
Technician/Programmer
Credit International
More information about the Python-list
mailing list