python-3.x 如何理解树节点类方法中的逻辑?

cbjzeqam  于 4个月前  发布在  Python
关注(0)|答案(1)|浏览(63)

下面是一个例子:

class TreeNode:

    def __init__(self, key, left=None, right=None, parent=None):
        self.key = key
        self.left_child = left
        self.right_child = right
        self.parent = parent

    def is_left_child(self):
        return self.parent and self.parent.left_child == self

字符串
对于方法“is_left_child(self)",为什么我们需要检查“self.parent”和“self.parent.left_child == self”的布尔值?

self.parent.left_child == self


检查self.parent的布尔值吗?它只是一个替代的写作:

if self.parent.left_child == self
    return True


?从而避免必须编写显式的“if”语句,并且仍然返回布尔值?

umuewwlo

umuewwlo1#

假设我创建一个节点:

a = TreeNode("a")

字符串
然后我创建另一个节点:

b = TreeNode("b", parent = a)


然后设置:

a.left_child = b


然后又道:

def is_left_child(self):
    return self.parent and self.parent.left_child == self


从类的is_left_child方法定义中取出self.parent:

def is_left_child(self):
    return self.parent and self.parent.left_child == self


它的工作正常。完整的代码:

class TreeNode:

def __init__(self, key, left=None, right=None, parent=None):
    self.key = key
    self.left_child = left
    self.right_child = right
    self.parent = parent

def is_left_child(self):
    return self.parent.left_child == self


自己试试:

a = TreeNode("a", 3)
b = TreeNode("b", 5, parent=a)
a.left_child = b
b.is_left_child()

   True

相关问题