Python 为什么uu getattribute_uuu失败:TypeError:';非类型';对象不可调用

Python 为什么uu getattribute_uuu失败:TypeError:';非类型';对象不可调用,python,typeerror,getattribute,Python,Typeerror,Getattribute,这是我在这里的第一个问题,也是我在Python中的第一个项目 print abcd.__getattribute__('hello') 我正在尝试存储名为Ip500Device的类的实例: class Ip500Device(object): list = [] def __init__(self, shortMac, mac, status, deviceType): self.__shortMac =shortMac self.__mac=

这是我在这里的第一个问题,也是我在Python中的第一个项目

print abcd.__getattribute__('hello')
我正在尝试存储名为
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
第一个测试只是一个“hello”,但在那之后,我想获得所有属性

从另一个类中,我正在创建devices对象并将其添加到列表中:

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中存储类实例

print abcd.__getattribute__('hello')
abcd.\uuuuu getattribute\uuuuuu
不是
\uuuuuuuuu getattribute\uuuuuu
方法。当您尝试计算
abcd.\uuuu getattribute\uuuu
时,您实际上是在调用

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

它返回
None
,然后您尝试将其作为一个方法调用。

发生错误的原因是对所有属性调用
\uuu getattribute\uuuu
,并且您已将其定义为对除“hello”之外的所有属性返回
None
。由于
\uuuu getattribute\uuuu
本身就是一个属性,当您尝试调用它时,您将得到一个
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
但是,最好定义
\uuuu getattr\uuuu
,因为它只对不存在的属性调用:

>>> 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
最后,请注意,如果您只想按名称访问属性,则可以使用内置函数:

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

我们得猜一下什么是
\uuu ip500DevicesLst
。OP非常清楚地指出
\uu ip500DevicesLst
是一个列表。但是,这与问题无关,问题是为什么调用
\uuuu getattribute\uuuu
会引发错误。OP提供了足够的信息来回答这个问题,所以我认为应该重新打开这个问题。列表中的一个项目似乎是
None
。不确定这是否来自您显示要附加到列表的方法调用,或者它是否已经包含
None
。无论哪种方式,请尝试验证列表内容是否符合预期。@Basic。否:
\uuuu getattribute\uuuu
是无条件调用的,因此为未处理的属性调用基类方法至关重要。OPs代码不这样做,所以当试图访问
\uuuu getattribute\uuuuu
属性本身时,它只返回
None
——因此出现了错误。@ekhumaro是的,你是对的。抢手货可调用的是
\uu getatribute\uuu