包含自己类型的子代列表的Python类出现意外的无限循环

时间:2018-08-15 15:18:37

标签: python

我正在学习Python中的类,并制作了一个可以包含其自身类型的子代的类,

class Control:
    def __init__(self, prompt="Prompt", children=[]):
        self.prompt = prompt
        self.children = children

    def addChild(self, child):
        self.children.append(child)

    def printXML(self):
        print(self.prompt)
        for child in self.children:
            child.printXML()

a = Control("control a")
b = Control("control b")

a.addChild(b)
a.printXML()

然后,我添加了printXML()方法,希望该方法列出嵌套在控件中的所有子控件。

此代码的预期输出:

control a
control b

但是相反,它会导致如下所示的无限循环:

control a
control b
control b
control b
control b
control b
control b
control b
control b
control b
control b
control b
...

似乎将b作为子级添加到a时,另一个b也作为子级添加到b中。我不知道为什么会这样。很抱歉这个愚蠢的问题。

0 个答案:

没有答案
相关问题