在节点树中,parent.addChild(self)是将self添加到self

发布于 2024-11-02 20:19:01 字数 780 浏览 1 评论 0原文

我正在用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一江春梦 2024-11-09 20:19:01

当您在类级别初始化子级时,类的每个实例最终都会共享相同的列表对象。

>>> class C:
...  children = []
... 
>>> a = C()
>>> b = C()
>>> id(a.children)
144349644
>>> id(b.children)
144349644

尝试在构造函数中初始化它:

def __init__(self, parent=None, tag="[ROOT]", attrs=None):
    self.children = []

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 = []
椒妓 2024-11-09 20:19:01

我怀疑 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文