如何在Python中为实体定义良好的数据结构?
我想用python处理实体。每个实体都有若干属性值对和若干类型。例如,“iPhone”作为一个实体,其AV对为:如何在Python中为实体定义良好的数据结构?,python,class,Python,Class,我想用python处理实体。每个实体都有若干属性值对和若干类型。例如,“iPhone”作为一个实体,其AV对为: Developer, Apple Inc CPU, Samsung Manufacturer, Foxconn 它有以下几种类型: smartphone mobilephone telephone 我希望为实体定义类。但是,我需要存储二维向量、属性值对和类型的信息。但是下面的代码不起作用。那么,我如何为这种实体定义一个好的数据结构(可能没有类) 您的代码中有语法错误-您不需要在
Developer, Apple Inc
CPU, Samsung
Manufacturer, Foxconn
它有以下几种类型:
smartphone
mobilephone
telephone
我希望为实体定义类
。但是,我需要存储二维向量、属性值对
和类型
的信息。但是下面的代码不起作用。那么,我如何为这种实体定义一个好的数据结构(可能没有类
)
您的代码中有语法错误-您不需要在类中的任何位置使用
[]
下面是一个示例,您可以使用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'],
},
)
您的代码中有语法错误-您不需要在类中的任何位置使用
[]
下面是一个示例,您可以使用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[]
进一步;理想情况下,您应该创建一个类实体和继承它的子类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
您的缩进有问题:
class entity:
def __init__(self, type, av[]):
self.type=type
self.av[]=av[]
进一步;理想情况下,您应该创建一个类实体和继承它的子类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
使用a,它是一个自写的类。使用a,它是一个自写的类。对于类型u,可以使用
*args
@matino,谢谢你的回答。我还有一个问题,我使用dict
作为属性。但是,如果iphone
有两个以上的属性,例如Manufacturer,Foxconn
和Manufacturer,Pegatron
,那么我使用dict[attribute]=value
,我只能得到一个项目。您可以使用list
作为值,并且可以有任意多个。我修改了我的示例。对于类型u,可以使用*args
@matino,谢谢您的回答。我还有一个问题,我使用dict
作为属性。但是,如果iphone
有两个以上的属性,例如Manufacturer,Foxconn
和Manufacturer,Pegatron
,那么我使用dict[attribute]=value
,我只能得到一个项目。您可以使用list
作为值,并且可以有任意多个。我修改了我的例子。