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

Create different objects by parsed text

1。 有包含形状信息的解析文本。 可能有 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']]]

2。 3 形状 classes 继承自 baseclass 'Shape':

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)

3。 我的问题是如何从解析的文本创建形状? 如何调用正确的构造函数以及如何传递正确的参数列表?我想以这种方式实现已解析参数的 link 和形状 classes:如果程序应该处理新形状(例如多边形),我只想创建一个新的 class 'Polygon'。 (例如 ['polygon', [['id', '151'], ['color', 11403055], ['x', '10'], ['y', '10'], ['corners', '7']]]) 执行此操作的 pythonic 方法是什么?

你可以这样做:

  • 对于每个参数 list 提取 class 名称,并使用字典获得真正的 class (否则,它需要评估大写名称,不是很 pythonic)
  • 获取参数 name/value 元组,并从中构建字典
  • 通过查询 name2class 字典中的 class 对象创建您的 class 实例,并使用 ** 表示法
  • 传递参数

代码:

param_list = [    ['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']]]]

name2class = {'circle':Circle, 'rectangle':Rectangle, 'triangle':Triangle}

for param in param_list:
    class_params = dict(param[1])  # dict from param tuples
    class_name = param[0]
    o = name2class[class_name](**class_params)

请注意,它目前在构建 Triangle 时阻塞,因为您缺少 2 个参数 axay。 列表中的参数必须与 __init__ 参数完全匹配,否则你会得到一个错误(至少是明确的)

要避免使用 name2class 字典,您可以这样做:

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

虽然 eval 的使用通常是矫枉过正并且存在严重的安全问题。您已收到警告。