在节点树中,parent.addChild(self)是将self添加到self
我正在用 python 构建一个简单的节点树。但是,当我的构造函数尝试将当前节点添加为给定父节点的子节点时,当前节点也会将其自身添加为自身的子节点。
这是我的构造函数方法(以及 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)
这是我在同一个类中的 addChild 方法(应该为父级调用,而不是当前正在构造的节点):
def addChild(self, child):
self.children.append(child)
这是输出:
foo []
foo [foo]
两行输出应该相同,因为它们之间的代码行应该只影响父节点,而不影响当前正在构建的节点。
我做错了什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您在类级别初始化子级时,类的每个实例最终都会共享相同的列表对象。
尝试在构造函数中初始化它:
When you initialize children at the class level every instance of your class ends up sharing the same list object.
Try initializing it in your constructor instead:
我怀疑
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.