2011-07-21 54 views
0
class Node: 
    children = {} 

sequence = [1,2,3,4,5] 

tree = Node() 
node = tree 
for item in sequence: 
    if item not in node.children: 
     node.children[item] = Node() 
    node = node.children[item] 

print tree.children.keys() 

我想要上面的代碼輸出[1],但它輸出[1, 2, 3, 4, 5]。爲什麼會這樣,我該如何解決它?python中的簡單樹實現的奇怪行爲

回答

7

Node.children是一個類屬性。將它改爲實例屬性。

class Node: 
    def __init__(self): 
    self.children = {}