在python中,当对象可能为None时,如何检查两个对象具有相同的属性值?
我有两个对象,我想检查它们是否具有相同的属性值。但是对象可以是 None。我有以下代码。除此之外,做同样的工作会更简单吗?
if obj1 is None and obj2 is None:
return True
if obj1 is None and obj2 is not None:
return False
if obj1 is not None and obj2 is None:
return False
if obj1.val != obj2.val:
return False
回答
整个事情归结为:
if obj1 is None or obj2 is None:
return obj1 is obj2 # we know at least one is None; are they both None?
return obj1.val == obj2.val # both are definitely not None, compare vals
if obj1 is None or obj2 is None:
return obj1 is obj2 # we know at least one is None; are they both None?
return obj1.val == obj2.val # both are definitely not None, compare vals
测试一下:
作为实际应用,这可以用作递归算法的一部分,以确定两个二叉树是否相同,如Leetcode: Same Tree。这可能解释了为什么您的最后一个条件obj1.val == obj2.valcase 丢失了,因为那是您的递归案例。
THE END
二维码