这是我之前的一个问题的延续
这是我的课。
#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)
生活中应该有一些项目,其中有一些项目。结构类似于这样(其中缩进是项目,-'s 是动作)
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() 正在返回每个项目,甚至是子项目。我做错了什么?