pythonclass

How to define a good data structure for an entity in Python?


I want to dealing entities with python. Each entity has several Attribute-Value pairs and several types. For example, "iPhone" as an entity, it has AV pairs as:

Developer, Apple Inc
CPU, Samsung
Manufacturer, Foxconn 

and it has types as:

smartphone
mobilephone
telephone

I wish to define class for the entity. However, I need to store the information of a 2-dimension vector, attribute-value pair and a type. But the code below does not work. So how can I define a good data structure for this kind of entity (perhaps without class)?

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

Solution

  • You have a syntax error in your code - you don't need [] anywhere in your class.

    Below is an example where you could use list for type information and dict for attributes:

    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'],
        },
    )