2017-01-15 6 views
2

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']]]) これを行うにはどうすればよいですか?

答えて

0

あなたはこれを行うことができます:(それは、非常にニシキヘビない大文字の名前を評価する必要になり、それ以外の)listは、クラス名を抽出し、それぞれのparamため

  • を、辞書を使って実際のクラスを取得し
  • name2class辞書からクラスオブジェクトを照会することによって、あなたのクラスのインスタンスを作成し、**表記
0123を使用してパラメータを渡す
  • それから、パラメータの名前/値のタプルを取得し、辞書を構築

    コード:Triangleを構築するときに、あなたが2つのパラメータaxayを逃しているので、それが現在チョークこと

    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) 
    

    ノート。 evalの使い方ですが

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

    :あなたができるname2class辞書を使用しないようにするに

    をリストから パラメータが正確に__init__パラメータと一致している必要があります。また、(少なくとも、明示的な)エラーが発生します通常は過度なセキュリティ問題があります。あなたは警告されています。

  • +0

    Triangleのコンストラクタで2パラメータの名前を変更した後、あなたのソリューションが正常に機能します! – Chris

    関連する問題