使用列表中的名称创建类的实例

时间:2017-05-27 11:24:33

标签: python list python-3.x dictionary

有一份清单

[[name1, value1], [name2, value2], ...]

我需要创建名称为name1,name2等的类的实例,即名称取自list[1][1]list[2][1]等。 但我无法想象如何实现这一点。

类别:

class func():
    def __init__(self, visibility, ftype, body):
    ...

列表:

list = [
    ['private', 'Void', 'SetupWheels', 'body'],
    ...
]

字典:

func_list = {}

它应该是这样的:

for i, val in enumerate(c):
    *new key in the dictionary is equal to the value val[2]* = func(val[0], val[1], val[3])

1 个答案:

答案 0 :(得分:0)

要使用属性来自列表列表的类的实例填充字典,您可以使用dict comprehension之类的:

代码:

func_list = {row[2]: Func(row[0], row[1], row[3]) for row in c}

测试代码:

class Func():
    def __init__(self, visibility, ftype, body):
        self.visibility = visibility
        self.ftype = ftype
        self.body = body

    def __repr__(self):
        return "v:%s f:%s b:%s" % (self.visibility, self.ftype, self.body)

c = [
    ['private', 'Void', 'SetupWheels', 'body'],
    ['private', 'Void', 'SetupWheelx', 'bo8y'],
]

func_list = {row[2]: Func(row[0], row[1], row[3]) for row in c}

print(func_list)

结果:

{'SetupWheelx': v: private f:Void b:body, 'SetupWheels': v: private f:Void b:body}