如何使用对象名称列表实例化对象

时间:2018-04-07 12:06:53

标签: python

我试图弄清楚如何从一串名称属性初始化一些对象。每个对象都将映射到字典键。这是基本的想法:

class Triangle(Shape):
    def __init__():
        Shape.__init__()
    name = "Triangle"

class Square(Shape):
    def __init__():
        Shape.__init__()
    name = "Square"

classTuple = (Triangle, Square)
classList = ["Triangle", "Square"]
classDict = {}

def initObjects():
    for shape in classList:
        for obj in classTuple:
            if obj.name == shape:
                classDict[shape] = obj(obj.sides, obj.corners #etc)

initObjects():

然而,唯一的问题是classTuple中的变量是未定义的,需要设置为类对象。怎么会这样做呢?

1 个答案:

答案 0 :(得分:0)

您的__init__()方法缺少self参数。另外,我建议使用super()方法。

class Triangle(Shape):
    def __init__(self):
        super().__init__()
    name = "Triangle"

class Square(Shape):
    def __init__(self):
        super().__init__()
    name = "Square"

classTuple = (Triangle, Square)
classList = ["Triangle", "Square"]
classDict = {}

def initObjects():
    for shape in classList:
        for obj in classTuple:
            if obj.name == shape:
                classDict[shape] = obj(obj.sides, obj.corners #etc)

initObjects()