2017-02-09 90 views
0

我有一個創建多重鏈接列表的類。每個節點可以有幾個(或一個或沒有)子節點。該節點有一個指向其最新子節點的指針,並且每個子節點都有一個指向其前一個兄弟節點的指針。所以我可以通過每個最新的孩子,然後每個兄弟姐妹輪流走完整棵樹。該函數遍歷三個成功,但沒有做任何有用的東西:通過對象鏈表傳遞函數

def walk_the_tree(self): 
    if not self.latestChild is None: 
     self.latestChild.walk_the_tree() 
    if not self.sib is None: 
     self.sib.walk_the_tree() 

現在,我真正想要做的是通過某種說法,這樣的成員函數可以在每個節點上執行。這裏的東西,將無法編譯,但我希望它得到什麼,我想:

def walk_the_tree(self, fcn): 
    self.fcn() 
    if not self.latestChild is None: 
     self.latestChild.walk_the_tree() 
    if not self.sib is None: 
     self.sib.walk_the_tree() 

所以,FCN可能是,例如,剛剛類__repr__,這樣我就可以得到所有節點上的所有信息很快。或者它可能是create_new_child(),它將確定節點是否需要新的子節點,如果是,則創建它。我希望用戶能夠在不依賴某種標誌的情況下選擇此選項。舉例來說,我不想是一樣的東西:

def walk_the_tree(self, fcnflg): 
    if (fcnflg == 1): self.__repr__() 
    if (fcnflg == 2): self.create_new_child() 
    if not self.latestChild is None: 
     self.latestChild.walk_the_tree() 
    if not self.sib is None: 
     self.sib.walk_the_tree() 

沒有辦法做到這一點?

+0

函數是第一類對象。所以它應該只是工作。不要執行'self.fnc'因爲這不會被定義。 –

+0

它絕對是一種OOP練習的氣味,但'obj.walk_the_tree(obj.create_new_child)'是你正在尋找的 – BlackBear

+0

是的,我只是把它作爲一個模塊級功能。 'def walk_tree(tree,f)'。儘管如此,我對保持簡潔的課程非常激進,這絕對是一種方法。 –

回答

1

問題是您正在使用self.fcn但未定義。只需使用fcn。這是一個人爲的例子:

>>> class MyContainer(object): 
...  def __init__(self, iterable=None): 
...   if iterable is not None: 
...    self.data = list(iterable) 
...   else: 
...    self.data = [] 
...  def walk_container(self, f): 
...   for x in self.data: 
...    print(f(x)) 
...  def _increment(self, x): 
...   return x + 1 
...  def print_increments(self): 
...   self.walk_container(self._increment) 
... 
>>> c = MyContainer([0,1,2]) 
>>> c.print_increments() 
1 
2 
3 
>>> 

或者,如果你願意,外部使用非方法:

>>> c.walk_container(lambda x: x**2) 
0 
1 
4 
>>>