2016-12-29 55 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,然后您可以尝试调用,好像它是一个方法。

相关问题