我试图弄清楚如何从一串名称属性初始化一些对象。每个对象都将映射到字典键。这是基本的想法:
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中的变量是未定义的,需要设置为类对象。怎么会这样做呢?
答案 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()