Reputation: 83
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.
Upvotes: 3
Views: 598
Reputation: 3807
Something like this? This retains the add_child function.
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)
Upvotes: 2
Reputation: 496
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
Upvotes: 5