python对象成员错误引用自己

时间:2018-04-05 15:02:14

标签: python

我想在单词列表上构建一个trie树基础,下面是节点类定义,节点的子节点是self.next_trees。

class Node(object):
    def __init__(self, charactor, tree_dict={}):
        self.charactor = charactor
        self.next_trees = tree_dict
        self.is_end = False

并使用此函数构建树

def build_tree(words):
    root = Node(None)
    for word in words:
        trace = root.next_trees
        for i,c in enumerate(word):
            if c not in trace:
                trace[c] = Node(charactor=c)

                pdb.set_trace()

                if i == len(word)-1:
                    trace[c].is_end = True
                else:
                    trace = trace[c].next_trees
            else:
                trace = trace[c].next_trees
return root

每当代码运行到断点时,对象" trace"指的是完全相同的对象" trace [c] .next_trees"指的是,而不是一个空洞的词典" {}" enter image description here

我将类似的代码复制到新的.py文件并运行,它不会再发生。为什么会发生这种情况?(python版本2.7.12)

1 个答案:

答案 0 :(得分:0)

您正在使用可变对象作为默认变量(tree_dict={})。试着这样做:

def __init__(self, charactor, tree_dict=None):
    if tree_dict is None:
        tree_dict = {}

tree_dict{})的默认值仅在构建__init__方法时计算, not 在调用时计算。然后存储该默认值,并在将来每次调用__init__时重复使用。这意味着所有<{1}}初始化的{/ 1}}实例都没有明确的Node值将使用此存储对象作为其tree_node,这意味着当您修改一个时,你也修改了所有其他人。