是的,将
__repr__代码移至
__str__,然后调用
str()您的树或将其传递给
__str__在递归调用中使用:
class node(object): def __init__(self, value, children = []): self.value = value self.children = children def __str__(self, level=0): ret = "t"*level+repr(self.value)+"n" for child in self.children: ret += child.__str__(level+1) return ret def __repr__(self): return '<tree node representation>'
演示:
>>> root = node('grandmother')>>> root.children = [node('daughter'), node('son')]>>> root.children[0].children = [node('granddaughter'), node('grandson')]>>> root.children[1].children = [node('granddaughter'), node('grandson')]>>> root<tree node representation>>>> str(root)"'grandmother'nt'daughter'ntt'granddaughter'ntt'grandson'nt'son'ntt'granddaughter'ntt'grandson'n">>> print root'grandmother' 'daughter' 'granddaughter' 'grandson' 'son' 'granddaughter' 'grandson'


