2009-07-25 109 views
3

這是one of my previous questions的延續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) 

生活中應該有一些項目,其中有一些項目。結構達這樣的事情(其中縮進項目和-'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()會返回每個項目,甚至是子項目。我做錯了什麼?

+0

很好的例子。現在我知道我妻子第二次懷孕後該怎麼辦。喝和彈吉他。在我的GTD捕獲工具中寫下來。 :) – 2009-07-28 06:39:33

回答

5

問題是與你的項目的初始化:

__init__(self, name, children=[]): 

你只有一個列表,這是您創建的所有項目沒有通過價值爲兒童共享。有關說明,請參閱here。您希望改爲默認None,並且只要該值爲None,就會初始化一個空列表。

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