2011-08-17 169 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 
相關問題