如前所述here,什麼時候使用hash()調用__eq__?
下面代碼,
class Person(object):
def __init__(self, name, ssn, address):
self.name = name
self.ssn = ssn
self.address = address
def __hash__(self):
print('in hash')
return hash(self.ssn)
def __eq__(self, other):
print('in eq')
return self.ssn == other.ssn
bob = Person('bob', '1111-222-333', None)
jim = Person('jim bo', '1111-222-333', 'sf bay area')
dmv_appointments = {}
print('calling hash')
dmv_appointments[bob] = 'tomorrow'
print('calling hash')
print(dmv_appointments[jim])
print('calling hash again')
print(dmv_appointments[bob])
輸出:
calling hash
in hash
calling hash
in hash
in eq
tomorrow
calling hash again
in hash
tomorrow
問題:
爲什麼__eq__
被調用訪問jim
而不是bob
?
我的猜測是,它首先檢查散列,然後_identity_(更快),只有_then_相等。因此,當你查看'bob'時,不必檢查'__eq__'來查看它是否是正確的入口,但是對於'jim'它確實。 –
相關問題:https:// stackoverflow。com/q/40917986/1639625一條評論說明了在C實現中它是如何完成的。 –
@tobias_k:是的,這是一個CPython(Python參考解釋器)實現細節,因爲[使用'PyObject_RichCompareBool'作爲比較C層對象的標準方法](https://docs.python.org/3/c -API/object.html#c.PyObject_RichCompareBool)。使用該函數進行相等性檢查實際上等同於Python級別的「返回x是y或x == y」。 – ShadowRanger