I have the this following class that specifies how to create a node. A node object has a name, a parent and a list of children.
I have one method to add children which works. Calling the add_child
method adds a child to the list of children. I first create a node with name 'A' and then add a child to A which has the name 'B'. One can check that a node with name attribute 'B' is then in the list of A's children. However I am unable to access this node object created (execept by calling A.children[0]
)
class Node:
def __init__(self,name,parent=None,children=[]):
#init defines the instance variables with . notation
self.name=name
self.children=children
self.parent=parent
def __str__(self):
return str('node'+' '+self.name)
def get_children(self):
children=self.children
names=[str(c) for c in children]
print(names)
return(children)
def add_child(self,child):
newchild=Node(child,self,children=[])
self.children.append(newchild)
A=Node('A',None,[])
A.add_child('B')
Is there any way for me to specify the reference to the new child object that has been created so that later I can access it easily withouth having to refer to the list of A's children?