【问题标题】:Tree data structure __str__ method树数据结构__str__方法
【发布时间】:2021-12-19 09:59:21
【问题描述】:
class TreeNode:
    def __init__(self,data,children = []):
        self.data = data
        self.children = children


    def __str__(self,level=0):
        ret = " " * level + str(self.data) + '\n'
        for child in self.children:
           ret += child.__str__(level+1)

        return ret

    # adding the children to the tree node
    def addchildren(self,TreeNode):
        self.children.append(TreeNode)

问题1:请解释def __str__(self,level=0):。特别是child.__str__(level+1)

drinks = TreeNode('Drinks',[])
cold = TreeNode('Cold',[])
hot = TreeNode('Hot',[])
cola = TreeNode('Cola',[])
cappucino = TreeNode('Cappucino',[])
drinks.addchildren(cold)
drinks.addchildren(hot)
cold.addchildren(cola)
hot.addchildren(cappucino)

print(drinks)

问题 2:还有一件事,如果我使用 self.children.append(TreeNode.data),为什么会出现这种类型错误(如下所示),我知道它不会起作用,但为什么 print() 语句会抛出此错误但不在self.children.append(TreeNode) 中。为什么它说 expected 0 arguments, got 1

TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_944/4195955341.py in <module>
----> 1 print(drinks)

~\AppData\Local\Temp/ipykernel_944/3676504849.py in __str__(self, level)
      8         ret = " " * level + str(self.data) + '\n'
      9         for child in self.children:
---> 10             ret += child.__str__(level+1)
     11 
     12         return ret

TypeError: expected 0 arguments, got 1

【问题讨论】:

    标签: python algorithm oop data-structures tree


    【解决方案1】:
    def __str__(self,level=0):
        ret = " " * level + str(self.data) + '\n'
        for child in self.children:
           ret += child.__str__(level+1)
    
        return ret
    

    " " * level 表示重复空间级别次数。 level 的默认值是 0 对象本身和级别加一为孩子,这些孩子再次调用他们的孩子的__str__ 水平增加一。所以当前对象在其行首有 0 个空格,它的孩子在其行首有 1 个空格,孩子的孩子在其行首有 2 个空格等等,这提供了类似于您在浏览时可能遇到的视觉表示目录例如:

    rootdir
     dir1
      dir11
      dir12
     dir2
      dir21
      dir22
    

    其中 dir11 和 dir12 在 dir1 中,dir21 和 dir22 在 dir2 中,dir1 和 dir2 在 rootdir 中。

    python__str__ 方法有多个参数(self 之外的任何参数)是不常见的。假设其中一个孩子是元组(1,2,3),那么当您尝试打印您的树时,它确实会尝试以等于1 的级别打印它,即

    (1,2,3).__str__(1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-30
      • 2010-10-30
      • 2013-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-24
      • 2011-05-18
      相关资源
      最近更新 更多