GTD app的复合模式

时间:2009-07-25 01:10:47

标签: python recursion composite gtd

这是one of my previous questions

的延续

这是我的课程。

#Project class     
class Project:
    def __init__(self, name, children=[]):
        self.name = name
        self.children = children
    #add object
    def add(self, object):
        self.children.append(object)
    #get list of all actions
    def actions(self):
        a = []
        for c in self.children:
            if isinstance(c, Action):
                a.append(c.name)
        return a
    #get specific action
    def action(self, name):
        for c in self.children:
            if isinstance(c, Action):
                if name == c.name:
                    return c
    #get list of all projects
    def projects(self):
        p = []
        for c in self.children:
            if isinstance(c, Project):
                p.append(c.name)
        return p
    #get specific project
    def project(self, name):
        for c in self.children:
            if isinstance(c, Project):
                if name == c.name:
                    return c

#Action class  
class Action:
    def __init__(self, name):
        self.name = name
        self.done = False

    def mark_done(self):
        self.done = True

这就是我遇到的麻烦。如果我构建一个包含多个小项目的大型项目,我想看看项目是什么或当前项目的操作,但是我在树中得到了所有项目。这是我正在使用的测试代码(请注意,我故意选择了几种不同的方法来添加项目和操作以进行测试,以确保不同的工作方式)。

life = Project("life")

playguitar = Action("Play guitar")

life.add(Project("Get Married"))

wife = Project("Find wife")
wife.add(Action("Date"))
wife.add(Action("Propose"))
wife.add(Action("Plan wedding"))
life.project("Get Married").add(wife)

life.add(Project("Have kids"))
life.project("Have kids").add(Action("Bang wife"))
life.project("Have kids").add(Action("Get wife pregnant"))
life.project("Have kids").add(Project("Suffer through pregnancy"))
life.project("Have kids").project("Suffer through pregnancy").add(Action("Drink"))
life.project("Have kids").project("Suffer through pregnancy").add(playguitar)

life.add(Project("Retire"))
life.project("Retire").add(playguitar)

生活中应该有一些项目,其中有一些项目。结构相当于这样(缩进是项目,而行为是动作)

Life
    Get Married
        Find wife
            - Date
            - Propose
            - Plan wedding
    Have kids
        - Bang wife
        - Get wife pregnant
        Suffer through pregnancy
            - Drink
            - Play guitar
    Retire
        - Play guitar

我发现life.actions()返回树中的每个动作,它应该不返回任何动作。当我只想要“结婚”,“有孩子”和“退休”时,life.projects()正在返回每个项目,甚至是子项目。我做错了什么?

1 个答案:

答案 0 :(得分:5)

问题在于您对Projects的初始化:

 __init__(self, name, children=[]):

您只能获得一个列表,该列表由您创建的所有项目共享,而不传递子项值。有关说明,请参阅here。您希望改为默认为None,并在值为None时初始化空列表。

 __init__(self, name, children=None):
    if children is None:
       children = []