这是我在这里的第一个问题,也是我在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中存储类实例。在
发生此错误是因为对所有属性调用了
__getattribute__
,并且您已经将其定义为返回None
,而不是“hello”。由于__getattribute__
本身是一个属性,当您尝试调用它时,您将得到一个TypeError
。在可以通过调用未处理属性的基类方法来解决此问题:
但是,最好定义
^{pr2}$__getattr__
,因为它只对不存在的属性调用:最后,请注意,如果您只想通过名称访问属性,则可以使用内置的getattr函数:
^{pr2}$abcd.__getattribute__
不是__getattribute__
方法。当您试图计算abcd.__getattribute__
时,实际上是在调用返回
None
,然后将其当作方法调用。在相关问题 更多 >
编程相关推荐