在方法中使用isintsance()通常很好。__eq__()但是,如果检查失败,您不应该False立即返回isinstance()- 最好返回NotImplemented以提供other.__eq__() 执行的机会:
def __eq__(self, other):
if isinstance(other, Trout):
return self.x == other.x
return NotImplemented
这在多个类定义的类层次结构中变得尤为重要__eq__():
class A(object):
def __init__(self, x):
self.x = x
def __eq__(self, other):
if isinstance(other, A):
return self.x == other.x
return NotImplemented
class B(A):
def __init__(self, x, y):
A.__init__(self, x)
self.y = y
def __eq__(self, other):
if isinstance(other, B):
return self.x, self.y == other.x, other.y
return NotImplemented
如果您False立即返回,就像您在原始代码中所做的那样,您将失去 和 之间的A(3) == B(3, 4)对称性B(3, 4) == A(3)。