开发者

Odd behaviour with simple tree implementation in python

class Node:
    children = {}

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

tree = Node()
node = tree
for item in sequence:
    if item not in node.childr开发者_开发问答en:
        node.children[item] = Node()
    node = node.children[item]

print tree.children.keys()

I want the above code to output [1], however it outputs [1, 2, 3, 4, 5]. Why is this, and how would I go about fixing it?


Node.children is a class attribute. Make it an instance attribute instead.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜