我需要Python中的樹數據結構從網站複製它,並遇到一些非常奇怪的問題。Python 3:獲取列表__repr__時超出最大遞歸深度
如果你創建了有兩個arguements它的工作對象,如果你只使用一個自變量,它在打印失敗,
RecursionError: maximum recursion depth exceeded while getting the repr of a list
我理解錯誤,但目前尚不清楚在哪裏以及爲什麼會發生。代碼也應該使用默認參數工作。我知道這是可變的。
class node(object):
def __init__(self, value, children = []):
self.value = value
self.children = children
def __repr__(self, level=0):
ret = "\t"*level+repr(self.value)+"\n"
for child in self.children:
ret += child.__repr__(level+1)
return ret
def add(self, value):
self.children.append(node(value))
#tree = node([1,4,3], [node([2,5,3])]) <-- works
tree = node([1,4,3]) # <-- fails
tree.add([3,4,3])
tree.add([4,4,3])
print(tree)
嘗試將'self.children = children'更改爲'self.children = children [:]' – thefourtheye