从列表中获取类对象

时间:2015-03-04 12:21:06

标签: python list class

如果我将类实例添加到多维列表中:

transList = []

class TransMsg(object):

    def __init__(self):

        self.canID   = ""
        self.msgType = ""
        self.canType = ""
        self.tData0  = ""
        self.tData1  = ""
        self.tData2  = ""
        self.tData3  = ""
        self.tData4  = ""
        self.tData5  = ""
        self.tData6  = ""
        self.tData7  = ""

        self.timer   = 0
        self.DLC     = 0


def addToList():

    global transList

    dictRef = len(transList)
    t = TransMsg()

    t.canID = "FF"
    t.DLC = 8
    t.canType = "s"
    t.msgType = "m"
    t.tData0 = "FF"
    t.tData1 = "FF"
    t.tData2 = "FF"
    t.tData3 = "FF"
    t.tData4 = "FF"
    t.tData5 = "FF"
    t.tData6 = "FF"
    t.tData7 = "FF"
    t.tTimer = "FF"

    transList.append([dictRef,t])

    print transList
    print transList[0][1]


if __name__ == '__main__':

    addToList()

 #output
 # [[0, <__main__.TransMsg object at 0xb75427ac>]]
 # <__main__.TransMsg object at 0xb75427ac>

我如何能够检索存储在TransMsg的t实例中的变量。例如,我如何能够从列表中打印tData0的值?

注意:必须通过列表变量transList执行此操作,因为这是更大项目的一部分。

由于

1 个答案:

答案 0 :(得分:2)

transList[0][1]将为您提供对t实例的引用。

transList[0][1].tData0应该有用。