簡體   English   中英

如何在Python中為實體定義良好的數據結構?

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

我想用python處理實體。 每個實體都有幾個“屬性-值”對和幾種類型。 例如,“ iPhone”作為實體,它具有以下AV對:

Developer, Apple Inc
CPU, Samsung
Manufacturer, Foxconn 

它具有以下類型:

smartphone
mobilephone
telephone

我希望為實體定義class 但是,我需要存儲二維向量, attribute-value pairtype 但是下面的代碼不起作用。 那么,如何為這種實體(也許沒有class )定義一個好的數據結構?

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

您的代碼中有語法錯誤-您在類中的任何地方都不需要[]

下面是一個示例,您可以在其中將list用於類型信息,將dict用於屬性:

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

您的縮進被弄亂了:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM