Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python GTD应用程序的复合模式_Python_Recursion_Composite_Gtd - Fatal编程技术网

Python GTD应用程序的复合模式

Python GTD应用程序的复合模式,python,recursion,composite,gtd,Python,Recursion,Composite,Gtd,这是本书的延续 这是我的课 #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

这是本书的延续

这是我的课

#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.actions()返回树中的每个操作,而它本不应该返回任何操作。当我只想“结婚”、“生孩子”和“退休”时,life.projects()会返回每个项目,甚至子项目。我做错了什么?

问题在于项目的初始化:

 __init__(self, name, children=[]):
您只会得到一个列表,该列表由您创建的所有项目共享,而不会为子项目传递值。请参阅以获取解释。您希望改为使用默认值None,并在值为None时初始化空列表

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

好例子。现在我知道当我妻子第二次怀孕时该怎么办了。喝酒,弹吉他。必须将其记录在我的GTD捕获工具中。:)
 __init__(self, name, children=[]):
 __init__(self, name, children=None):
    if children is None:
       children = []