“object”不带“none”类型的“错误”

2024-10-03 09:09:29 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我试图存储名为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对象并将它们添加到列表中:

^{pr2}$

但当我尝试打印时,程序会返回以下消息:

TypeError: 'NoneType' object is not callable

我不太了解如何在Python中存储类实例。在


Tags: 项目实例selfhelloobjectinitmacdef
2条回答

发生此错误是因为对所有属性调用了__getattribute__,并且您已经将其定义为返回None,而不是“hello”。由于__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__,因为它只对不存在的属性调用:

^{pr2}$

最后,请注意,如果您只想通过名称访问属性,则可以使用内置的getattr函数:

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

abcd.__getattribute__不是__getattribute__方法。当您试图计算abcd.__getattribute__时,实际上是在调用

^{pr2}$

返回None,然后将其当作方法调用。在

相关问题 更多 >