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开发者_JAVA百科 ... 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?
When you initialize children at the class level every instance of your class ends up sharing the same list object.
>>> class C:
... children = []
...
>>> a = C()
>>> b = C()
>>> id(a.children)
144349644
>>> id(b.children)
144349644
Try initializing it in your constructor instead:
def __init__(self, parent=None, tag="[ROOT]", attrs=None):
self.children = []
I suspect children
is 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.
精彩评论