Python的dict要求key為不可變數據類型,通常采用str或int,但在某些應用場景下,需要采用自定義類型對象作key,
此時的自定義類需要實現兩個特殊方法:__hash__、__eq__,用於哈希值的獲取和比較
定義狗類:
class Dog(): def __init__(self,name,color): self._n = name self._c = color def __hash__(self): return hash(self._n + self._c) def __eq__(self,other): return (self._n,self._c)==(other._n,other._c)
定義房子:
from dog import Dog dog_1 = Dog(name = 'mike',color = 'red') dog_2 = Dog(name = 'tom',color = 'blue') dog_3 = Dog(name = 'tom',color = 'blue') #房子里有兩只狗
house = {} house[dog_1] = 1 house[dog_2] = 2
#每只狗對應的哈希值
print(hash(dog_1)) print(hash(dog_2)) print(hash(dog_3)) #輸出每只狗的編號
for item in house: print(house[item]) #名字和顏色相同的狗是同一只
print(house[dog_3]==2) >>1019109570234974571
>>5676435319618840106
>>5676435319618840106
>>1
>>2
>>True
參考:
http://www.mamicode.com/info-detail-495084.html
https://blog.csdn.net/woshiaotian/article/details/20286149