Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating recursive class tree with children in python

Tags:

python

Even searching through many similar questions I could not find how I could create recursive class tree structure (adding branch with leaves to the root) in python. Maybe someone could advice why this type of code does not work in python and how it should be written correctly?

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 library works for creating this structure but it is difficult to adapt that in the full project.

like image 694
Eva Avatar asked Sep 01 '26 22:09

Eva


1 Answers

your class doesnt have a constructor, so all objects shared the same list. here's the correct python syntax:

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

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

an example showing class variables vs. instance variables:

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
like image 185
Jonathan Avatar answered Sep 04 '26 11:09

Jonathan