简体   繁体   English

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

[英]Creating instances of a class with names from a list

There is a list of lists 有清单清单

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

I need to create instances of a class with names name1, name2, and so forth, ie, with names taken from the list[1][1] , list[2][1] , etc. But I can't imagine ways in which this can be implemented. 我需要创建一个名称为name1,name2等的类的实例,即使用从list[1][1]list[2][1]等中获取的名称。但是我无法想象在其中可以实现。

Class: 类:

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

List: 列表:

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

Dictionary: 字典:

func_list = {}

It should look like this: 它看起来应该像这样:

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])

To populate a dictionary with instances of a class whose attributes were taken from a list of lists, you can use a dict comprehension like: 要使用一个类的实例来填充字典,该类的属性是从列表中获取的,您可以使用dict理解,例如:

Code: 码:

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

Test Code: 测试代码:

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)

Results: 结果:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM