【问题标题】:Odd behaviour with simple tree implementation in pythonpython中简单树实现的奇怪行为
【发布时间】:2011-07-21 05:08:34
【问题描述】:
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 class tree


    【解决方案1】:

    Node.children 是一个类属性。改为将其设为实例属性。

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

    【讨论】:

      猜你喜欢
      • 2013-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-25
      • 2018-04-25
      • 2013-05-28
      • 1970-01-01
      • 2021-12-02
      相关资源
      最近更新 更多