[Python] dict(自定义类作key)


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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM