1

我正在尝试制作具有递归“printAll”方法的树。

我的代码是:

class Node(object):
    def __init__(self, children=[], tag=None):
        self.children = children
        self.tag = tag

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

    def getChildren(self):
        return self.children

    def printAll(self):
        print self.getChildren()
        for child in self.children:
            child.printAll()

当我运行它时,我得到这个:“调用 Python 对象时超出了最大递归深度”。

我猜这与在调用孩子的 printAll() 方法时将顶级范围传递给孩子有关,从而导致无限循环。任何帮助深表感谢。

4

1 回答 1

2

尝试更改您的默认值children

class Node(object):
    def __init__(self, children=None tag=None):
        self.children = children if children is not None else []
        self.tag = tag

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

    def getChildren(self):
        return self.children

    def printAll(self):
        print self.getChildren()
        for child in self.children:
            child.printAll()

您可能遇到“可变默认参数”的情况

于 2013-02-20T01:32:06.877 回答