Using isintsance()
is usually fine in __eq__()
methods. You shouldn't return False
immediately if the isinstance()
check fails, though -- it is better to return NotImplemented
to give other.__eq__()
a chance of being executed:
def __eq__(self, other):
if isinstance(other, Trout):
return self.x == other.x
return NotImplemented
This will become particularly important in class hierarchies where more than one class defines __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
If you would return False
immediately, as you did in your original code, you would lose symmetry between A(3) == B(3, 4)
and B(3, 4) == A(3)
.