python面试题之面向对象and内置函数

用到知识

1、面向对象
2、内置函数__hash__
3、内置函数__eq__

一、试题简介

1、定义一个类,然后类中对象的属性有:姓名,性别,年龄,部门
2、假设几年后,内部员工转岗了,
3、到了另一个岗位后,姓名,性别,年龄新的部门,在另一个员工表有了新的数据
4、然后我认定,假设员工对象的姓名和性别一致,那么我就认定这是一个人
5、去重,筛选

1、说到去重,首先想到 set集合
2、然后,与 set 有关的内置函数  __hash__,__eq__
3hash算法,我自定义了hash的方法,让他只计算员工的 name 和 sex,如果 hash 的值相同
4、那么就执行 __eq__ 这个函数,然后判断它们的 name and  sex 是否相同
5、相同就去重。
6、最后打印出来,测试结果
 
class Employee:
    def __init__(self,name,age,sex,partment):
        self.name = name
        self.age = age
        self.sex = sex
        self.partment = partment

    def __hash__(self):
        '''判断 hash 值是否相等'''
        return hash('%s %s' %(self.name,self.sex))

    def __eq__(self,other):
        '''如果 hash 相等的话,然后就会触发 __eq__方法
        来判断他们的  name 和 sex 是否相等,然后再来去重'''
        if self.name == other.name and self.sex == other.sex:
            return True

employee_list = []
for i in range(200):
	'''假设创建了两百个员工,但是年龄不同'''
    employee_list.append(Employee('mayun',i,'man','entrepreneur'))
for i in range(200):
    employee_list.append(Employee('mahuateng',i,'man','entrepreneur'))
for i in range(200):
    employee_list.append(Employee('liuqiangdong',i,'man','entrepreneur'))

# print(employee_list)
employee_list = set(employee_list)

for person in employee_list:
    print(person.__dict__)


#使用  set  后先触发 hash 判断,如果hash相等的话,这时候就会触发__eq__
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值