Is this an Intended behaviour of __getattr__?

Volucris volucris at hotmail.com
Fri Jul 27 03:04:16 EDT 2001


"Grace" <nospam at nospam.com> wrote in message
news:uu787.103805$ph7.16107665 at news.hananet.net...
> 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,
>
>  __str__ was called...
> __repr__ was called...
> <__main__.Node instance at 0081608C>
>  __str__ was called...
> __repr__ was called...
> <__main__.Node instance at 0081608C>
>  __str__ was called...
> __repr__ was called...
> <__main__.Node instance at 0081601C>
>  __str__ was called...
> __repr__ was called...
> <__main__.Node instance at 0081601C>
> al was called...
> Traceback (most recent call last):
>   File "...", line 22, in ?
>     print f.al
>   File "...", line 12, in __getattr__
>     k=3/0
> ZeroDivisionError: integer division or modulo by zero
>
> 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.
>
>

in __getattr__ if the attr is 'next', if checks the value of _next and
returns whether it's None or not. the code after return never gets executed.
the only time it didn't return first, was when __getattr__ was called with
'errorPlz' (not 'next').

That was too wordy, but I hope it's intelligible.
--

Volucris (a) hotmail.com
"Eu não falo uma única palavra do português."





More information about the Python-list mailing list