class.__getattr__ behavior: feature or bug?

Jeff Bauer jbauer at rubic.com
Fri Jan 14 16:52:41 EST 2000


Tim, Huayin:

Raising an AttributeError exception in the __getattr__()
method fixes Huayin's problem, assuming Tim's suggestion
isn't applied. <wink>:

class S:
    def __init__(self):
        self.a = 0
    def __getattr__(self, name):
        if name == 'c':
            self.a = self.a + 1
            return self.a
        else:
            raise AttributeError, name

if __name__ == '__main__':
    s = S()
    print "s.a =", s.a
    print "s.c =", s.c
    print "s =", s
    try:
        print "s.b =", s.b
    except AttributeError:
        "AttributeError 's.b' not found"

---
Jeff Bauer
Rubicon Research

Tim Peters wrote:
> 
> [Huayin Wang]
> > >>> 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.




More information about the Python-list mailing list