I am trying to make a class to be used for some sort of tree graph. The class has the following attributes: value, label, children and parent. In Python I have the following lines of code:
import numpy as np
class testclass:
def __init__(self, v, l, c=[], P = np.nan):
self.value = v
#self.parent = p
self.children = c
self.parent = P
self.label = l
def addChild(self, node):
self.children.append(node)
The method addChild
is supposed to simply add one instance to the list known as children of the current instance. However, when I run the following:
> Node1 = testclass(1,'x')
> Node2 = testclass(2, 'y')
> Node1.children.append(Node2)
for some reason this adds Node2
as a child to Node1 and itself. Node2's children shouldn't have changed but calling Node2.children
yields a non-empty list! What am I doing wrong?
Edit: I saw that the question here seems to showcase a similar problem. But I still cannot get my head around a solution for my case. I have tried calling the append method directly in the console: > Node1.children.append(Node2)
and have also tried defining it by
def addChild(self, nodec):
self.children += [nodec]