RecursionError:Python类中的最大递归深度超出错误

时间:2019-05-23 19:13:56

标签: python recursion

我正在尝试从我的Node类中以文本格式获取子级列表。我需要它以便能够以JSON格式打印结构。

当我尝试调用getchildren()方法或直接在__str__中使用相同的代码时,在两种情况下,我都会遇到最大递归错误。它带有“上一行已执行196次”。

我有一些解决方案说增加该限制,可能会解决我的问题,如果没有其他办法,我将尝试尝试解决此问题,但无法知道为什么会出现此错误。

这就像是我试图创建一个本应是XML的JSON一样,因此它非常嵌套并且源是CSV文件,代码显示了一个数据节点。

对于Python来说是很新的东西,类似的东西在Java中效果很好,所以很困惑。

我有此代码:

class Node:
    _attributeDictionary = {}
    _lst = []

    def __init__(self, tag):
        self._tag = tag

    def setAttribute(self, attributeName, attributeValue):
        self._attributeDictionary [attributeName]= attributeValue

    def setChild(self, node):
        self._lst.append(node)

    def getchildren(self):
        s = "["
        for l in self._lst:
            s = s + str(l) + "],"
        return s[:-1]

    def __str__(self):
        s = "["
        for l in self._lst:
            s = s + str(l) + "],"
        return "'" + self._tag + "':" + str(self._attributeDictionary) + "," + s[:-1] + ""


nodeA=Node("A")
nodeA.setAttribute("attA","valA")
nodeB=Node("B")
nodeB.setAttribute("attA","valB")
nodeA.setChild(nodeB)
print(str(nodeA))

错误:

s = s + str(l) + "],"
[Previous line repeated 196 more times]
RecursionError: maximum recursion depth exceeded

0 个答案:

没有答案
相关问题