Python 树数据类型添加子操作会导致递归子项



>我在python上生成了一棵树,我只是想将一个新的子节点附加到父节点,但是,尽管子节点no的子节点是空的,但似乎发生了子节点成为父节点和自身的子节点

def __init__(self):
self.child_nodes = []
self.data = None
...
self.parent = None
def init_tree(self, data, child_nodes=[], ...):
self.child_nodes = child_nodes
self.data = data
...
def add_child_node(self, node):
ancestors = self.get_ancestors()
if node is not self and node not in ancestors:
self.child_nodes.append(node)
node.parent = self
def get_ancestors(self):
ancestor = self.parent
ancestors = [ancestor]
try:
while ancestor.parent != None:
ancestors.append(ancestor)
parent = self.parent
ancestor = parent.get_parent()
return ancestors
# Node is root. Root's parent is None
except AttributeError:
return []

def my_funct(self):
...
child_node = RandomWalkTree()       
child_node.init_tree(data=data)
self.add_child_node(child_node)

my_funct会产生一个子节点,其child_nodes递归地包含自身。我错过了哪些点?

我已经找到了解决方案并分享了具有类似解决方案的解决方案。初始化函数中的行

self.child_nodes = child_nodes

结果我已将其更改为

self.child_nodes = [] 

并删除了参数。问题解决了。

最新更新