首页 > 解决方案 > 如何最好地为我的树类编写一个 __str__ 方法?

问题描述

我有一个名为Tree

class Tree:
    def __init__(self, tag, children):
        self.tag = tag
        self.children = children
    def __str__(self):
        pass

这是我班级的一个示例对象:

tree = Tree('A', [Tree('B', [Tree('C', [])]), Tree('D', [Tree('E', [])])])

现在我希望当我打印我的树时,它看起来像下面这样:

(A (B C) (D E))

我的想法是遍历嵌套的 Trees 并检查直到找到一个空列表,它告诉我这个空列表属于我的树的一个叶子。然后我从那里向上构建它并在我的标签和孩子周围添加括号。

标签: pythonclassmethodstree

解决方案


迭代方法可能会起作用,但我认为递归在这里更合适。

class Tree:
    def __init__(self, tag, children):
        self.tag = tag
        self.children = children

    def __str__(self):
        # Recursively build up the full string
        if self.children:
            return f'({self.tag} {" ".join(str(child) for child in self.children)})'
        # Base case - no children; Just return the tag.
        else:
            return self.tag

这将产生你想要的字符串:

>>> tree = Tree('A', [Tree('B', [Tree('C', [])]), Tree('D', [Tree('E', [])])])
>>> print(tree)
(A (B C) (D E))

IMO,像这样将子子项分组在自己的括号中会更有意义(为清楚起见,添加了额外的“F”节点):

(A (B (C)) (D (E)) (F))

您可以通过将elsereturn 括在括号中来做到这一点:

class Tree:
    ...

    def __str__(self):
        ...
        else:
            return f'({self.tag})'

但是,当然,这取决于您的用法是否正确:)


推荐阅读