在python中用孩子创建递归类树

时间:2019-07-04 13:22:36

标签: python

即使通过许多类似的问题进行搜索,我也找不到如何在python中创建递归类树结构(将带有叶子的分支添加到根中)。也许有人会建议为什么这种类型的代码在python中不起作用以及如何正确编写?

import copy

class Tree:
    children = []

    def add_child(self, child):
        self.children.append(copy.deepcopy(child))

level1 = Tree() 
child_level2 = Tree()
child_level3 = Tree()
child_level2.add_child(child_level3)
print('After adding level 3 to level 2 children number is {}'.format(len(child_level2.children)), child_level2.children)

level1.add_child(child_level2)
print('After adding level 2 to level 1, level 1 children number is {} but expecting expecting to have 1 child'.format(len(level1.children)), level1.children)
print('After adding level 2 to level 1, level 2 children number is {} but expecting expecting to have 1 child'.format(len(level1.children[0].children)),level1.children[0].children)

p.s。 Anytree库可用于创建此结构,但是很难在整个项目中进行调整。

2 个答案:

答案 0 :(得分:2)

您的类没有构造函数,因此所有对象共享同一列表。这是正确的python语法:

class Tree:
    def __init__(self):
        self.children = []

    def add_child(self, child):
        self.children.append(copy.deepcopy(child))

显示类变量与实例变量的示例:

class Tree1:
    class_children = []

    def __init__(self):
        self.children = []


node1 = Tree1()
node2 = Tree1()
child = Tree1()

node1.children.append(child)
node1.class_children.append(child)
print('node1 children length: {}'.format(len(node1.children)))  # 1
print('node2 children length: {}'.format(len(node2.children)))  # 0

print('node1 class_children length: {}'.format(len(node1.class_children)))  # 1
print('node2 class_children length: {}'.format(len(node2.class_children)))  # 1

答案 1 :(得分:2)

像这样?这保留了add_child函数。

class Tree:
    def __init__(self):
        self.children = []

    def add_child(self, child):
        self.children.append(child)

level1 = Tree() 

level2 = Tree()
level1.add_child(level2)

level3 = Tree()
level2.add_child(level3)

print('After adding level 2 to level 1, level 1 children number is {} but expecting expecting to have 1 child'.format(len(level1.children)), level1.children)
print('After adding level 2 to level 1, level 2 children number is {} but expecting expecting to have 1 child'.format(len(level1.children[0].children)),level1.children[0].children)