class Person:
def __init__(self, name, age, job):
self.name = name
self.age = age
self.job = job
# 重写函数返回属性
def __str__(self):
return f"{self.name}--{self.age}--{self.job}"
# 冒泡排序法
def bubble_sort(my_list: list[Person]):
"""
冒泡排序,从大到小排列
:param my_list:
:return:
"""
# j控制总排序次数
for j in range(len(my_list) - 1):
# i控制每次排序比较的次数
for i in range(len(my_list) - 1 - j):
# 当列表中后一个的年龄大于前一个的年龄时,交换
if list[i].age < list[i + 1].age:
# 两数交换
list[i], list[i + 1] = list[i + 1], list[i]
p1 = Person("tom", 35, "老师")
p2 = Person("amy", 18, "学生")
p3 = Person("jack", 52, "校长")
list = [p1, p2, p3]
print("排列前".center(32, "_"))
# 遍历列表
for i in range(len(list)):
print(list[i])
# 使用sort进行排序
'''
key=lambda ele:ele.age--表示我指定按照列表元素的age属性进行排序
reverse=True--表示逆序-从大到小排列
reverse=False--表示顺序-从小到大排列
'''
list.sort(key=lambda ele: ele.age, reverse=False)
print("从小到达排列后".center(32, "_"))
for i in range(len(list)):
print(list[i])
# 调用冒泡排序函数
bubble_sort(list)
print("从大到小排列后".center(32, "_"))
for i in range(len(list)):
print(list[i])
class Doctor:
def __init__(self, name, age, job, gender, sal):
self.name = name
self.age = age
self.job = job
self.gender = gender
self.sal = sal
# 重写eq方法
def __eq__(self, other):
# 首先判断比较直是否为同类
if not isinstance(other,Doctor):
return False
else:
return (self.name == other.name
and self.age == other.age
and self.job == other.job
and self.gender == other.gender
and self.sal == other.sal)
p1 = Doctor("tom", 28, "护士", "女", 10000)
p2 = Doctor("tom", 28, "护士", "女", 10000)
# p1==p2默认会调用__eq__方法
print("p1==p2",p1==p2)