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]
。为什么会这样,我将如何解决它?
答案 0 :(得分:7)
Node.children
是一个类属性。改为使其成为实例属性。
class Node:
def __init__(self):
self.children = {}