I’m building a simple node tree in python. But when my constructor tries to add the current node as a child of a given parent, the current node also adds itself as a child of itself.
Here’s my constructor method (and the creation of children):
children = []
def __init__(self, parent=None, tag="[ROOT]", attrs=None):
self.parent = parent
self.tag = tag
self.attrs = attrs
print "\n", "self:%s ... children:%s" % (self.tag, self.children)
if parent != None:
parent.addChild(self)
print "self:%s ... children:%s" % (self.tag, self.children)
Here’s my addChild method in the same class (which is supposed to be called for the parent, not the node currently under construction):
def addChild(self, child):
self.children.append(child)
Here’s the output:
foo []
foo [foo]
The two lines of output should be the same because the line of code between them should only affect the parent node, not the node currently under construction.
What am I doing wrong?
I suspect
childrenis somehow shared across all of your node objects; we can’t see the declaration so I can’t say exactly what you’re doing wrong.