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)
中抛出此错误
。为什么它说 预期 0 个参数,得到 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
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__
方法具有超过 1 个参数(超过 self
的任何参数)的情况并不常见。假设其中一个子元素是元组(1,2,3)
,那么当您尝试打印树时,它会尝试打印级别等于1
的树,即
(1,2,3).__str__(1)
我其实也有和问题一样的问题。 2. 当我们在初始化节点时向列表中添加子节点时,它会抛出位置参数。 示例
cold = TreeNode('冷', ['酒精', '非酒精'])