【问题标题】:Python 3: maximum recursion depth exceeded while getting the __repr__ of a listPython 3:获取列表的 __repr__ 时超出了最大递归深度
【发布时间】:2015-10-15 10:30:22
【问题描述】:

我需要一个 Python 中的树形数据结构,我从网站上复制了它,但遇到了一些非常奇怪的问题。

如果你创建一个带有两个参数的对象,它会起作用,如果你只使用一个参数,它会在打印时失败

RecursionError: 获得最大递归深度 列表的代表

我了解错误,但不清楚它发生在哪里以及为什么会发生。代码也应该使用默认参数工作。我知道它是可变的。

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[:]

标签: python


【解决方案1】:

你的默认参数中有一个可变对象

    def __init__(self, value, children = []):

这会导致children 的单个列表实例,因此当您构建第二个列表时,您的子列表随后将添加到该默认列表中,因此 每个 迭代都将在该列表中遍历,从而导致这个无限循环。

你应该这样做

    def __init__(self, value, children=None):
        self.value = value
        if children is None:
             children = []
        self.children = children

或者你也可以

        self.children = children or []

两者都分配了一个新的列表实例来解决这个问题。

【讨论】:

  • 谢谢!经过一段时间的思考,我自己得到了它!我不应该从网站上复制不良代码...
猜你喜欢
  • 1970-01-01
  • 2016-07-09
  • 2011-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-19
  • 2011-10-12
  • 2020-07-13
相关资源
最近更新 更多