python-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()返回每个项目,甚至子项目.我做错了什么事?
解决方法:
问题在于您对Projects的初始化:
__init__(self, name, children=[]):
您只会得到一个列表,该列表将由您创建的所有项目共享,而不会传递子代的值.有关说明,请参见here.您想改为设置默认值None,并且每当值为None时就初始化一个空列表.
__init__(self, name, children=None):
if children is None:
children = []
标签:gtd,python,composite,recursion 来源: https://codeday.me/bug/20191024/1920594.html