简单的自己的树体系结构使子节点倍增

时间:2018-10-25 06:26:36

标签: python

我正在尝试做一个简单的树,每个孩子的名字。

这是最少的代码:

class Node:
   def __init__(self, msg, childs={}):
       self.msg = msg
       self.childs=childs

tree = Node('1')
tree.childs['2'] = Node('2')
tree.childs['3'] = Node('3')

执行print(tree.childs)给我一个预期的输出:

  

{'3':主要。页面对象位于0x7f1fda9f77b8>,'2':主要。页面对象位于0x7f1fda9f77f0>}

但是执行print(tree.childs['2'].childs)给我:

  

{'3':主要。页面对象位于0x7f1fda9f77b8>,'2':主要。页面对象位于0x7f1fda9f77f0>}

预期输出为:

  

{}

我在哪里错了?为什么我错了?

2 个答案:

答案 0 :(得分:4)

mutable default argument的典型问题。改为:

class Node:
    def __init__(self, msg, childs=None):
        self.msg = msg
        self.childs = childs or {}

答案 1 :(得分:3)

您不应将{}之类的可变对象作为__init__方法的默认值,因为它的引用将被后续调用重用,并且对该可变对象的任何更改都将反映在其他具有相同引用的变量。

将您的__init__方法更改为:

class Node:
   def __init__(self, msg, childs=None):
       self.msg = msg
       self.childs=childs or {}