【问题标题】:can someone explain me this line有人可以解释一下这条线吗
【发布时间】:2020-07-09 05:10:58
【问题描述】:
class TreeNode:
    def __init__(self, data):
        self.data = data
        self.children = []
        self.parent = None

    def get_level(self):
        level = 0
        p = self.parent
        while p:
            level += 1
            p = p.parent

        return level

    def print_tree(self):
        spaces = ' ' * self.get_level() * 3
        prefix = spaces + "|__" if self.parent else ""
        print(prefix + self.data)
        if self.children:
            for child in self.children:
                child.print_tree()

    def add_child(self, child):
        child.parent = self
        self.children.append(child)

def build_product_tree():
    root = TreeNode("Electronics")

    laptop = TreeNode("Laptop")
    laptop.add_child(TreeNode("Mac"))
    laptop.add_child(TreeNode("Surface"))
    laptop.add_child(TreeNode("Thinkpad"))

    cellphone = TreeNode("Cell Phone")
    cellphone.add_child(TreeNode("iPhone"))
    cellphone.add_child(TreeNode("Google Pixel"))
    cellphone.add_child(TreeNode("Vivo"))

    tv = TreeNode("TV")
    tv.add_child(TreeNode("Samsung"))
    tv.add_child(TreeNode("LG"))

    root.add_child(laptop)
    root.add_child(cellphone)
    root.add_child(tv)

    root.print_tree()

if __name__ == '__main__':
    build_product_tree()

我知道 self.parent 的含义,但请有人解释一下:p = p.parent 和 child.parent = self

【问题讨论】:

  • 在某些时候p.parent 将导致None 将停止循环,然后您将计算循环运行的次数。
  • 通过p = p.parent,我们提升了一代人。因此,当当前节点有父节点时,将父节点设置为当前节点并增加级别。 child.parent = self 表示将child 节点的父节点设置为当前节点(self)

标签: python python-3.x oop


【解决方案1】:

想象一下你有一大堆水桶。最小的红色,大一点的橙色,大一点的黄色,彩虹的所有颜色。

你把红色放在橙色里面,然后你把橙色放在黄色里面,以此类推。您的所有存储桶现在都在其他存储桶中。除了紫罗兰。这是最大的桶。

现在你从红色桶开始。我们称之为self。我们想要一个算法来计算有多少桶。让我们创建一个名为 level 的计数器变量。

红色桶的父节点是橙色桶,我们可以使用p = self.parent获取。现在p 指的是橙色桶。我们还想给我们的计数器加 1。所以我们做level += 1。

现在p 是橙色的桶。但我们还没有完成。我们需要找出橙色桶是否也有父桶。我们将询问其父级,并通过说p = p.parent 重用相同的变量p。在我们这样做之后,p 变成黄色桶。然后我们再次向关卡添加一个。

我们一直这样下去,直到我们到达紫罗兰色桶。紫水桶是最外层的水桶。所以当我们向紫罗兰桶询问它的父母时,我们不会得到答案。换句话说,当p是紫桶,而我们做p = p.parent时,p就不再是桶了!

好吧,只要p 仍然是一个桶,我们就只是在循环。在代码中,这就是while p: 的含义。所以现在我们停止循环,我们的level 变量告诉我们有多少桶。

child.parent = self 告诉桶去哪里。让我们来一个更大的桶。一个黑色的桶。我们称之为self。我们还会得到紫罗兰色桶。我们称之为child。现在,我要告诉紫水桶进入黑水桶。 child.parent = self.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-09
    • 2021-12-06
    • 2017-09-02
    • 2011-07-12
    相关资源
    最近更新 更多