day30 小面试题 去重 (考核 __eq__ 以及 __hash__ )

时间:2023-03-09 16:31:28
day30 小面试题 去重 (考核 __eq__ 以及 __hash__ )
 # 小面试题,要求将一个类的多个对象进行去重
# 使用set方法去重,但是无法实现,因为set 需要依赖eq以及hash,
# hash 哈希的是内存地址, 必然不一样
# eq 比较的也是内存地址,必然也不一样
# 因此需要对 hash 和 eq 的功能进行更改 class A:
def __init__(self, name, sex, age):
self.name = name
self.sex = sex
self.age = age def __hash__(self):
return hash(self.name + self.sex) def __eq__(self, other):
if self.name == other.name and self.sex == other.sex:
return True
return False a = A("egg", "nan", 18)
b = A("egg", "nan", 18)
print(set((a, b))) # set 依赖对象的hash eq 方法