使用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)