class A: def __init__(self,name,age): self.name = name self.age = age def __eq__(self, other): if self.name == other.name and self.age ==other.age: return True a = A("dudu",99) aa = A("dudu",99) print(a,aa) print(a == aa)
面试题
# 一个类,对象的属性姓名,性别,年龄,部门 # 员工管理系统 # 内部转岗 python开发 - go开发 # 姓名,性别,年龄,新的部门 # 1000个员工 # 如果员工性别和姓名相同,这是一个人 class Employee: def __init__(self,name,age,sex,partment): self.name = name self.age = age self.sex = sex self.partment = partment def __hash__(self): return hash("%s%s" %(self.name,self.sex)) def __eq__(self, other): if self.name == other.name and self.sex == other.sex: return True employee_lst = [] for i in range(200): employee_lst.append(Employee("yan",i,"male","py")) for i in range(200): employee_lst.append(Employee("liu",i,"male","py")) for i in range(200): employee_lst.append(Employee("jie",i,"male","py")) for i in range(200): employee_lst.append(Employee("yu",i,"male","py")) for i in range(200): employee_lst.append(Employee("dudu",i,"male","py")) # print(employee_lst) print(set(employee_lst)) # set去重机制 先调用hash,再调用eq,eq不是每次都会触发,只有hash值相等才会触发