【发布时间】:2021-08-22 05:21:16
【问题描述】:
class TreeNode:
def __init__(self,data):
self.data=data
self.children = []
self.parent = None
def add_child(self,child):
**child.parent=self** ---- PLease explain this line. I am not getting it.
self.children.append(child)
def build_product_tree():
root = TreeNode('Electronics')
laptop= TreeNode('Laptop')
root.add_child(laptop)
return root
当我们添加孩子时,我们给 child.parent=self 我不明白这一点。请问有人解释一下吗?
【问题讨论】:
-
在执行
child.parent=self时,self是对root的引用,因为代码执行root.add_child(laptop)。这会将对象root传递给add_child()作为self。这就是.的意思。