每个Person的python类设计都有N个项目,每个项目都有M个东西

时间:2017-09-20 11:09:40

标签: python

如果方案是: Person'sPerson,每个Projects可以有N Project,每个Things可以有M class Person(): def __init__(self): self.projects=Project() class Project(): def __init__(self): self.project=[] some_one=Person() some_one.projects.project.extend(["project1", "project2"]) print(some_one.projects.project) ['project1', 'project2'] 。 到目前为止,我实现了如下课程:

project

问题是我想要将things连接到class Person(): def __init__(self): self.projects=Project() class Project(): def __init__(self): self.project=[] self.things=Thing() class Thing(): def __init__(self): self.thing="thing" some_one=Person() some_one.projects.project.extend(["project1", "project2"])

some_one.projects.project1.things.thing1="some_one's project1's thing1"

我想要类似的东西:

trait

2 个答案:

答案 0 :(得分:1)

如果Person可以有多个Project,则应该包含Project的集合。
如果Project可以有多个Thing,那么它应该包含“Thing”的集合 然后,您可以按照描述的方式处理属性。

class Person():
    def __init__(self):
        self.projects = []   # a collection of Project

class Project():
    def __init__(self):
        self.things = []     # a collection of Thing

class Thing():
    def __init__(self):
        # this thing attributes

答案 1 :(得分:1)

似乎Person应该有一个Project列表,而Project应该有一个Thing列表。

class Person():
    def __init__(self):
        self.projects = []

class Project():
    def __init__(self):
        self.things = []

class Thing():
    def __init__(self):
        self.thing = 'thing'

所以例如

thing_a = Thing()
thing_b = Thing()
thing_c = Thing()

project_a = Project()
project_a.things = [thing_b, thing_c]

project_b = Project()
project_b.things = [thing_a, thing_b]

someone = Person()
someone.projects = [project_a, project_b]

然后你可以说

>>> someone.projects[0].things[0].thing
thing