奇怪的行为与python中的简单树实现

时间:2011-07-21 05:08:34

标签: python class tree

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]。为什么会这样,我将如何解决它?

1 个答案:

答案 0 :(得分:7)

Node.children是一个类属性。改为使其成为实例属性。

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