1 # 小面试题,要求将一个类的多个对象进行去重 2 # 使用set方法去重,但是无法实现,因为set 需要依赖eq以及hash, 3 # hash 哈希的是内存地址, 必然不一样 4 # eq 比较的也是内存地址,必然也不一样 5 # 因此需要对 hash 和 eq 的功能进行更改 6 7 class A: 8 def __init__(self, name, sex, age): 9 self.name = name 10 self.sex = sex 11 self.age = age 12 13 def __hash__(self): 14 return hash(self.name + self.sex) 15 16 def __eq__(self, other): 17 if self.name == other.name and self.sex == other.sex: 18 return True 19 return False 20 21 22 a = A("egg", "nan", 18) 23 b = A("egg", "nan", 18) 24 print(set((a, b))) # set 依赖对象的hash eq 方法