python dict key类型_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))

你可能感兴趣的:(python,dict,key类型)