我正在創建創建節點及其子節點的基本樹。但是在使用 print() 陳述句時出現錯誤,即 __ str __( ) 在下面的代碼中列印出樹布局。
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.data)
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)
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
為什么它會拋出這個 TypeError?解決辦法是什么?我期待這個:
Drinks
Cold
Cola
Hot
Cappucino
還有一件事,請也解釋一下def __str__(self,level=0):方法,特別是child.__str__(level_1)因為我借用了這個列印陳述句。
uj5u.com熱心網友回復:
你的addchildren方法壞了,它應該添加TreeNode到self.children,而不是TreeNode.data:
def addchildren(self,TreeNode):
self.children.append(TreeNode)
該TypeError是造成ret = child.__str__(level 1),是指可以遞回子節點,如果每個孩子self.children也是類的一個實體TreeNode。但它失敗并導致TypeError因為TreeNode.data被添加為孩子之一。
如錯誤訊息TypeError: expected 0 arguments, got 1所示,它嘗試呼叫內置類的實體 的__str__方法TreeNode.data,str默認情況下不帶任何引數。因為__str__用戶定義類的方法TreeNode被覆寫了,而內置str類沒有。
因此它與 invoking 相同'Cold'.__str__(level 1),默認情況下不需要任何引數。
目的。str (self) 由 str(object) 和內置函式 format() 和 print() 呼叫以計算物件的“非正式”或可很好列印的字串表示。回傳值必須是字串物件。-- Python3 參考
請注意,self這并不算作引數(至少不在錯誤訊息中),它只是一種約定,將每個類方法需要作為引數串列中第一個放置的物件的參考。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/350527.html
下一篇:找到通過頂點u和v的最小權重回路
