这是本书的延续
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()会返回每个项目,甚至子项目。我做错了什么?