When I run this code:
class Node:
children = []
num_children = 0
isleaf = True
def __init__(self,name):
print("constructor called for " + name)
self.name = str(name)
def add_child(self,child_node):
print("adding child called "+child_node.name+ " to "+ self.name)
print("I ("+self.name+ ") have " + str(len(self.children)) + " children")
print("checking: " + child_node.name + " reports " + str(len(child_node.children)) + " children")
#cc = copy.deepcopy(child_node)
self.children.append(child_node)
#self.children.append(1)
#self.children[0] = child_node
print("checking again: " + child_node.name + " reports " + str(len(child_node.children)) + " children")
self.isleaf = False
self.num_children = self.num_children +1
print("I ("+self.name+ ") now have " + str(len(child_node.children)) + " children")
root = Node("a")
testn = Node("b")
root.add_child(testn)
print(root.children[0].name)
I get this output:
constructor called for a
constructor called for b
adding child called b to a
I (a) have 0 children
checking: b reports 0 children
checking again: b reports 1 children
I (a) now have 1 children
b
why does the line of code:
self.children.append(child_node)
add a child to the child (B
) as well as the parent (A
)?
I would expect it to only add a child to the parent (A
)