使用类对象列表调用类函数Python

时间:2017-02-24 20:52:05

标签: python python-2.7

我有一个类,当我定义类时,我传递了各种值(IP地址,名称,模型等)。

同时我将这些类放入列表中,这样我就可以轻松扩展设备数量。我希望能够从班级中调用一个单独的函数。

例如

我的课看起来有点像

class foo:
    def __init__(self, IP, Name, Model, Series):
         #Do stuff
    def getstate():
         #Do more stuff and return a value

我的列表看起来有点像

Devices = {}    #I fill this up with the list of all devices elseware
ClassDevices = []

for key in Devices:
        print 'List is empty, store objects'
        ClassDevices.append(Foo(Devices[key]["IP"], Devices[key], Devices[key]["Model"], Devices[key]["Series"]))

以上似乎有效但现在我希望能够获得每个设备的状态。我试过以下

print ClassDevices[0].getstate()

我收到错误

TypeError: object cannot be interpreted as an index

我是Python的新手,所以我甚至不确定我想做什么是可能的

可以看到完整代码(因为它可能更容易)here

1 个答案:

答案 0 :(得分:0)

你要做的事情很简单。主要问题是你没有正确迭代(因为你不熟悉Python)。

你有一段代码如下:

for x in SmartHome.SenseMeDevices:
    print(SmartHome.SenseMeDevices[x].getstate())

在这种情况下,x 已经是列表中的元素,而不是元素的索引。

你应该这样迭代:

for x in SmartHome.SenseMeDevices:
    print(x.getstate())