我不明白为什么会出现这种情况,我仍在努力学习python调试。你知道吗
class Node():
def __init__(self, parent = None, children = [], data = None):
self.parent = parent
self.children = children
self.data = data
if parent == None:
self.root = self
else:
self.root = self.parent.root
def add_child(self, child):
self.children.append(child)
child.parent = self
def is_root(self):
return self.root == self
def is_leaf(self):
return self.children == []
def is_empty(self):
return self.data == None
def pprint(self):
def _pprint(ast, l):
if not self.is_empty():
print(l * " ", self.data)
if not self.is_leaf():
for child in self.children:
_pprint(child, l + 1)
_pprint(self, 0)
我这样使用代码:
root = Node()
root.add_child(Node(data="a"))
root.pprint()
一段时间后,pprint方法会给出一个异常:
...
File "ll.py", line 56, in _pprint
_pprint(child, l + 1)
File "ll.py", line 56, in _pprint
_pprint(child, l + 1)
File "ll.py", line 56, in _pprint
_pprint(child, l + 1)
File "ll.py", line 56, in _pprint
_pprint(child, l + 1)
File "ll.py", line 52, in _pprint
if not self.is_empty():
File "ll.py", line 48, in is_empty
return self.data == None
RecursionError: maximum recursion depth exceeded in comparison
我认为“基本情况”应该是叶节点,没有子节点。我错过了什么?你知道吗
所有节点都将使用相同的可变对象
children
。 这导致children
像一个全局变量。你知道吗阅读更多here。你知道吗
可能的解决方法:
编辑:
当然,您还想在
_pprint
函数中写入ast
,而不是self
:相关问题 更多 >
编程相关推荐