【问题标题】:Create different objects by parsed text通过解析的文本创建不同的对象
【发布时间】:2017-01-15 16:40:04
【问题描述】:

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 个形状类继承自基类“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。 我的问题是如何从解析的文本中创建形状? 如何调用正确的构造函数以及如何传递正确的参数列表?我想以这种方式实现已解析参数和形状类的链接:如果程序应该处理新形状(例如多边形),我只想创建一个新类“多边形”。 (例如['polygon', [['id', '151'], ['color', 11403055], ['x', '10'], ['y', '10'], ['corners', '7']]]) 这样做的pythonic方法是什么?

【问题讨论】:

    标签: python text dynamic parameters init


    【解决方案1】:

    你可以这样做:

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

    代码:

    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 时会阻塞,因为您缺少两个参数 axay。 列表中的参数必须与__init__ 参数完全匹配,否则您将收到错误(至少是显式的)

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

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

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

    【讨论】:

    • 在 Triangle 的构造函数中重命名 2 参数后,您的解决方案工作正常!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-27
    • 1970-01-01
    • 2014-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多