我正在尝试创建一棵具有递归“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/