Search code examples
pythongetattr

Why does this __getattr__ function not work?


I've got this little class I wrote to try playing with custom __getattr__ methods, and every time I run it, I get an Attribute error:

class test:
    def __init__(self):
        self.attrs ={'attr':'hello'}
    def __getattr__(self, name):
        if name in self.attrs:
            return self.attrs[name]
        else:
            raise AttributeError

t = test()
print test.attr

The output is then:

Traceback (most recent call last):
  File "test.py", line 11, in <module>
    print test.attr
AttributeError: class test has no attribute 'attr'

What gives? I thought getattr was called before an attribute error was raised?


Solution

  • Because the class test doesn't have attr as an attribute, the instance t does:

    class test:
        def __init__(self):
            self.attrs ={'attr':'hello'}
        def __getattr__(self, name):
            if name in self.attrs:
                return self.attrs[name]
            else:
                raise AttributeError
    
    t = test()
    print t.attr