2016-04-13 15 views
0

私はPythonでエンティティを扱いたいと思っています。各エンティティには、複数の属性 - 値ペアと複数のタイプがあります。例えばエンティティとして、 "iPhone"、それはのようにAVペアを有する:Pythonでエンティティに適切なデータ構造を定義する方法は?

Developer, Apple Inc 
CPU, Samsung 
Manufacturer, Foxconn 

、それがタイプを有するもの:

smartphone 
mobilephone 
telephone 

Iは、エンティティのclassを定義したいです。しかし、私は二次元ベクトルの情報、attribute-value pairtypeを格納する必要があります。しかし、以下のコードは動作しません。だから、私はどのようにこの種のエンティティのために良いデータ構造を定義できますか(おそらくclassなし)?

class entity: 
def __init__(self, type, av[]): 
    self.type=type 
    self.av[]=av[] 
+0

それ自身を書き、クラスである[namedtuple](https://docs.python.org/3/library/collections.html#collections.namedtuple)を使用します。このような何か。タイプUの – msw

答えて

3

あなたはあなたのコードの構文エラーを持っている - あなたは、あなたのクラスで[]どこにも必要ありません。以下は

あなたは、属性の型情報とdictためlistを使用することができます例です。

class Entity: 

    def __init__(self, types, attributes): 
     self.types = types 
     self.attributes = attributes 

iphone = Entity(
    types=['smartphone', 'mobilephone', 'telephone'], 
    attributes={ 
     'Developer': ['Apple Inc'], 
     'CPU': ['Samsung'], 
     'Manufacturer': ['Foxconn', 'Pegatron'], 
    }, 
) 
+0

は '* args'を使用できます – qvpham

+0

@matino、あなたの答えに感謝します。さらに質問があります。属性に 'dict'を使用します。しかし、 'iphone'に' Manufacturer、Foxconn'や 'Manufacturer、Pegatron'のような2つ以上の属性がある場合は、' dict [attribute] = value'を使用します。 – flyingmouse

+0

値には 'list'を使い、好きなだけ多く使うことができます。私は私の例を修正しました。 – matino

2

あなたのインデントを台無しにされています。また、

class entity: 
    def __init__(self, type, av[]): 
     self.type=type 
    self.av[]=av[] 

。理想的にはクラスEntityとそれを継承するサブクラスのIPhoneを作成する必要があります。すべての属性は、リスト属性内の値だけでなく、クラス属性でなければなりません。

class Entity(object): 
    def __init__(self, type): 
     self.type = type 
    ... attributes and methods common to all entities 

class IPhone(Entity): 
    def __init__(self, developer, cpu, manufacturer): 
     Entity.__init__(self, "smartphone") 
     self.developer = developer 
     self.cpu = cpu 
     self.manufacturer = manufacturer 
関連する問題