Python无限递归打印所有子项

标签 python class recursion

我正在尝试创建一棵具有递归“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() 方法时将顶级范围传递给子级有关,从而导致无限循环。非常感谢任何帮助。

最佳答案

尝试更改您的默认子项:

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()

您可能遇到 "mutable default argument" 的情况

关于Python无限递归打印所有子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14970730/

相关文章:

python - 为什么我尝试在 Python 2.7 中打印字符串时遇到错误?

java - 错误整数自定义值Java

python - 为什么我的代码打印 'None' ?

c++ - 使用递归打印链表元素

python - ruamel.yaml - 缩进序列不起作用?

python - 遍历两个数组并将每个数组的集合添加到新数组中而不重复

c++ - 创建顺序类对象

excel - 在VBA中递归打印下一个字典

c - 按值将数组传递给递归函数可能吗?

python - 如何检查文件是否为空