Python 通过解析文本创建不同的对象

Python 通过解析文本创建不同的对象,python,text,dynamic,parameters,init,Python,Text,Dynamic,Parameters,Init,一,。 存在包含形状信息的已解析文本。 3种不同的形状是可能的:圆形,矩形,三角形 已解析的参数具有以下形式: ['circle', [['id', '11'], ['color', 11403055], ['x', '10'], ['y', '10'], ['radius', '20']]] ['rectangle', [['id', '2'], ['color', 10494192], ['x', '10'], ['y', '20'], ['width', '10'], ['height',

一,。 存在包含形状信息的已解析文本。 3种不同的形状是可能的:圆形,矩形,三角形

已解析的参数具有以下形式:

['circle', [['id', '11'], ['color', 11403055], ['x', '10'], ['y', '10'], ['radius', '20']]]
['rectangle', [['id', '2'], ['color', 10494192], ['x', '10'], ['y', '20'], ['width', '10'], ['height', '10']]]
['triangle', [['id', '7'], ['color', 16716947], ['ax', '50'], ['ay', '15'], ['bx', '15'], ['by','40'], ['cx', '100'], ['cy', '100']]]
二,。 3个形状类继承自基类“形状”:

class Shape(object):
    def __init__ (self, id, color, x, y):
        self.__id = id
        self.__color = color
        self.__p = g.Point2d(x, y)
 class Circle(Shape):
    def __init__ (self, id, color, x, y, radius):
        self.__type = "circle"
        self.__radius = radius
        super(Circle, self).__init__(id, color, x, y)

class Rectangle(Shape):
    def __init__ (self, id, color, x, y, width, height):
        self.__type = "rectangle"
        self.__dim = g.Point2d(width, height)
        super(Rectangle, self).__init__(id, color, x, y)

class Triangle(Shape):
    def __init__ (self, id, color, x, y, bx, by, cx, cy):
        self.__type = "triangle"
        self.__b = g.Point2d(bx, by)
        self.__c = g.Point2d(cx, cy)
        super(Triangle, self).__init__(id, color, x, y)
三,。 我的问题是如何从解析的文本中创建形状? 如何调用正确的构造函数以及如何传递正确的参数列表?我想以这种方式导入解析参数和形状类的链接:如果程序应该处理一个新的形状(例如多边形),我只想创建一个新的类“多边形”。 (例如,
['polygon'、['id'、['151']、['color',11403055]、'x'、'10']、['y'、'10']、['corners','7']].
) 蟒蛇式的方法是什么?

你可以这样做:

  • 对于每个param
    list
    提取类名,并使用字典获取真正的类(否则,需要计算大写的名称,而不是非常pythonic)
  • 获取参数名称/值元组,并从中构建字典
  • 通过从
    name2class
    字典查询类对象来创建类实例,并使用
    **
    符号传递参数
代码:

请注意,在构建
三角形时,它当前会阻塞,因为您缺少两个参数
ax
ay
。 列表中的参数必须与
\uuuuu init\uuuuu
参数完全匹配,否则将出现错误(至少是显式的)

要避免使用
name2class
字典,可以执行以下操作:

class_name = param[0].capitalize()
o = eval(class_name)(**class_params)

尽管
eval
的使用通常是过度的,并且存在严重的安全问题。您已收到警告。

在重命名三角形构造函数中的2参数后,您的解决方案工作正常!
class_name = param[0].capitalize()
o = eval(class_name)(**class_params)