2011-08-17 270 views
0

我有个小类我写了尝试与定制__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之前调用属性错误?

回答

8

因为类testattr作为属性,实例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

现在我觉得很傻... – Alex

+0

这也发生在我身上,很多次。 – agf

4

你要查询的属性上实例t),而不是在test):

>>> t = test() 
>>> print t.attr 
hello 
相关问题