【发布时间】: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