day30 __hash__ 计算哈希值

hash()  # __hash__
哈希的时候会根据内存地址进行哈希,因为地址不同所以哈希的值也不同,哪怕是完全一样子的属性得出的哈希值也不一样
因此存在需要某些时刻期望属性相同得出相同哈希值
可以控制对象的哈希值是否相等,或者规定改变

 1 class B:
 2     def __init__(self,name,sex):
 3         self.name = name
 4         self.sex = sex
 5 a = B("yangtuo","tiancai")
 6 b = B("yangtuo","tiancai")
 7 # 默认是哈希内存地址
 8 print(a)    # <__main__.B object at 0x000000000251D240>
 9 print(b)    # <__main__.B object at 0x000000000251D4E0>
10 print(hash(a)==hash(b))        # False


11 class A: 12 def __init__(self,name,sex): 13 self.name = name 14 self.sex = sex 15 def __hash__(self): 16 return hash(self.name + self.sex) 17 a = A("suyang","") 18 b = A("suyang","") 19 print(hash(a)) # -7714351582186626821 20 print(hash(b)) # -7714351582186626821 21 print(hash(a)==hash(b)) # True

猜你喜欢

转载自www.cnblogs.com/shijieli/p/9938543.html