为什么__getattr__函数不起作用?

时间:2011-08-17 18:36:11

标签: python getattr

我已经编写了这个小班,尝试使用自定义__getattr__方法,每次运行时,都会出现属性错误:

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

然后输出:

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

是什么给出的?我认为在引发属性错误之前调用了 getattr

2 个答案:

答案 0 :(得分:8)

由于班级test attr作为属性,因此实例t执行:

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

答案 1 :(得分:4)

您必须查询实例t)上的属性,而不是test):

>>> t = test()
>>> print t.attr
hello