2016-12-29 27 views
1

這是我的第一個問題,也是我在Python中的第一個項目。爲什麼__getattribute__失敗:TypeError:'NoneType'對象無法調用

我想存儲一個名爲Ip500Device類的實例:

class Ip500Device(object): 

    list = [] 
    def __init__(self, shortMac, mac, status, deviceType): 
     self.__shortMac =shortMac 
     self.__mac=mac 
     self.__status=status 
     self.__deviceType=deviceType 
     self.__nbOfObjects=0 
     Ip500Device.list.append(self)  

    def __getattribute__(self, att): 
     if att=='hello': 
      return 0 

這第一個測試只是一個「你好」,但在那之後我想獲得的所有屬性。

從其他類,我創建的設備對象並將其添加到列表:

self.__ip500DevicesLst.append(Ip500Device.Ip500Device(lst[0],lst[1],lst[2],lst[3])) 
for abcd in self.__ip500DevicesLst: 
     print abcd.__getattribute__('hello') 

但是,當我嘗試打印,程序返回此消息:

TypeError: 'NoneType' object is not callable 

我不太瞭解如何在Python中存儲類實例。

+3

我們必須猜測'__ip500DevicesLst'是什麼。 –

+1

該OP非常清楚地指出'__ip500DevicesLst'是一個列表。但是,這與問題無關,這就是爲什麼調用'__getattribute__'引發錯誤。 OP已經提供了足夠的信息來回答這個問題,所以我認爲這個問題應該重新開放。 – ekhumoro

+0

看起來像列表中的一個項目是'None'。不知道這是來自您顯示附加到列表的方法調用,還是已經包含「None」。無論哪種方式,請嘗試驗證列表內容是否符合預期。 – Basic

回答

0

的錯誤是因爲__getattribute__被調用所有屬性,並且您已經定義它返回None比「你好」等應有盡有。由於__getattribute__本身就是一個屬性,所以當您嘗試調用它時,您將得到TypeError

這個問題可以通過調用未處理的屬性基類的方法來固定:

>>> class Ip500Device(object): 
...  def __getattribute__(self, att): 
...   print('getattribute: %r' % att) 
...   if att == 'hello': 
...    return 0 
...   return super(Ip500Device, self).__getattribute__(att) 
... 
>>> abcd = Ip500Device() 
>>> abcd.__getattribute__('hello') 
getattribute: '__getattribute__' 
getattribute: 'hello' 
0 

但是,它是更好地界定__getattr__,因爲這是唯一需要的,它已經不存在的屬性:

>>> class Ip500Device(object): 
...  def __getattr__(self, att): 
...   print('getattr: %r' % att) 
...   if att == 'hello': 
...    return 0 
...   raise AttributeError(att) 
... 
>>> abcd = Ip500Device() 
>>> abcd.hello 
getattr: 'hello' 
0 
>>> abcd.foo = 10 
>>> abcd.foo 
10 

最後,請注意,如果你想要做的名字是訪問屬性,你可以使用內置的getattr功能:

>>> class Ip500Device(object): pass 
... 
>>> abcd = Ip500Device() 
>>> abcd.foo = 10 
>>> getattr(abcd, 'foo') 
10 
1
print abcd.__getattribute__('hello') 

abcd.__getattribute__不是__getattribute__方法。當您嘗試評估abcd.__getattribute__,你實際上調用

type(abcd).__getattribute__(abcd, '__getattribute__') 

返回None,然後您可以嘗試調用,好像它是一個方法。

相關問題