下面是一个例子:
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”语句,并且仍然返回布尔值?
1条答案
按热度按时间umuewwlo1#
假设我创建一个节点:
字符串
然后我创建另一个节点:
型
然后设置:
型
然后又道:
型
从类的is_left_child方法定义中取出self.parent:
型
它的工作正常。完整的代码:
型
自己试试:
型