Is this an Intended behaviour of __getattr__?

Grace nospam at nospam.com
Fri Jul 27 02:09:46 EDT 2001


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.







More information about the Python-list mailing list