2016-01-20 37 views
0
class Node: 
    def __init__(self,parent = None): 
     self.parent = parent 
     self.children = [] 
    def AddNode(self): 
     self.children.append(Node(self)) 
    def getIndex(self): 
     return self.parent.children.index(self) 

a = Node() 
b = a.AddNode() 
print b.getIndex() 

在像上面那樣的對象樹中,孩子在父級孩子中找出其索引的最佳方式是什麼?我正在使用self.parent.children.index(self),但似乎扭曲。有沒有更好的辦法?找到嵌套Python對象的自我索引

回答

1

一個尼特:這不太合適,因爲AddNode不會返回任何東西。 除此之外,你已經做得很好。只要您按索引(懶惰)檢索索引,就可以直接執行此操作。如果你想要更直接的東西,我建議你在AddNode鏈接孩子時存儲索引。

class Node: 

    def __init__(self,parent = None): 
     self.parent = parent 
     self.children = [] 
     self.child_index = None 

    def AddNode(self): 
     new_child = Node(self) 
     self.children.append(new_child) 
     new_child.child_index = self.children.index(new_child) 
     return new_child 

    def getIndex(self): 
     return self.child_index 

a = Node() 
b = a.AddNode() 
c = a.AddNode() 
d = a.AddNode() 

print d.getIndex() 
print c.getIndex() 
print b.getIndex() 

輸出(booooorrriiinnngg):

2 
1 
0 
+0

就確認我需要的,謝謝。是的,感謝提醒在AddNode()中返回一些內容。正如你可能已經猜到的那樣,我真正的代碼是這樣做的,但我忘了在示例中添加它。乾杯! – Adam

+0

很高興能有所幫助。記住當你點擊一個節奏點時「接受」一個答案:它可以讓StackOverflow正確地解決問題。 – Prune