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 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 个回答
5
问题出在你对 Projects 的初始化上:
__init__(self, name, children=[]):
你只得到一个列表,这个列表被你创建的所有 Projects 共享,因为你没有为 children 传递一个值。想了解更多,可以查看 这里 的解释。你应该把默认值改成 None,然后在值为 None 的时候初始化一个空列表。
__init__(self, name, children=None):
if children is None:
children = []