2024-03-29 11:54:30 发布
网友
我需要塑造家庭、父母、孩子和普通人的实体。我该怎么做? 很明显,我可以创造4个甚至5个不同的班级:家庭,两个父母,一个孩子和一个人。 但我认为这种方法有冗余。另一方面,如果我引入一个字段“type”是family、mother等,那么我必须为family和其他东西创建一个也可以为null的字段引用。你知道吗
你的建议?你知道吗
在这种情况下,我认为简单地有两个类是有意义的,例如
class Person: def __init__(self, name): self.name = name class Family: def __init__(self): self.children = [] self.parents = []
然后Family.children和Family.parents可以是Person对象的列表,其中可以有任意数量的子对象或父对象。你知道吗
Family.children
Family.parents
Person
如果要存储关系,还可以向Person添加更多属性,例如Person可以有其.siblings或.parents或.children的成员
.siblings
.parents
.children
在这种情况下,我认为简单地有两个类是有意义的,例如
然后
Family.children
和Family.parents
可以是Person
对象的列表,其中可以有任意数量的子对象或父对象。你知道吗如果要存储关系,还可以向
Person
添加更多属性,例如Person
可以有其.siblings
或.parents
或.children
的成员相关问题 更多 >
编程相关推荐