【问题标题】:Python infinite recursion in printing all childrenPython无限递归打印所有孩子
【发布时间】:2013-02-20 09:32:06
【问题描述】:

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

【问题讨论】:

标签: python class recursion


【解决方案1】:

尝试更改您的默认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()

你可能有"mutable default argument"的案例

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-27
    • 2021-11-04
    • 1970-01-01
    相关资源
    最近更新 更多