【发布时间】: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