第一题
设计一个学生类
属性:姓名、学号、年龄、成绩
设计一个班级类要求:实现向班级中添加学生、删除学生、查看学生、按照指定条件排序
属性:班级代号,所有学生
需要使用
calss, __int__, __str__, sort, append, dict, list, remove, for in
class stu:
# 设置学生基础属性
def __init__(self, name, num, age, cj):
self.name = name
self.num = num
self.age = age
self.cj = cj
def __str__(self):
return '姓名:{},学号:{},年龄:{},成绩{}'.format(self.name, self.num, self.age, self.cj)
# 查看学生类是否创建成功
# c = stu('小米', 100, 18, 66)
# print(c)
class class1:
def __init__(self, name):
self.name = name
self.class_dict = {}
self.class_list = []
def add_stu(self, stu):
# 添加学生至对应字典列表
self.class_dict[stu.num] = stu
self.class_list.append(stu)
def del_stu(self, num):
# 弹出后删除
stu_danchu = self.class_dict.pop(num)
self.class_list.remove(stu_danchu)
def sort_stu(self, key, reverse=false):
# 排序
self.class_list.sort(key=key, reverse=reverse)
def show_class(self):
# 打印
print(self.name)
for i in self.class_list:
print(i)
def chazhao_stu(self, num):
return print(self.class_dict.get(num))
# 测试代码
import random
c1 = class1('python')
for i in range(10):
name = 'stu' + str(i)
num = 100 + i
age = random.randint(18, 25)
cj = random.randint(70, 100)
c = stu(name, num, age, cj)
c1.add_stu(c)
# 展示
c1.show_class()
# 排序
c1.sort_stu(key=lambda s: s.num, reverse=true)
# 查找
c1.chazhao_stu(108)
# 删除
c1.del_stu(109)
c1.show_class()
如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!