使用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)
之間的對稱。
我認爲這是'isinstance'的合法用例。 – 2012-03-23 17:15:48