第一题
- 设计一个学生类
- 属性:姓名、学号、年龄、成绩
- 设计一个班级类要求:实现向班级中添加学生、删除学生、查看学生、按照指定条件排序
- 属性:班级代号,所有学生
- 需要使用
- 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()
原文地址:https://www.cnblogs.com/wenjiangtao/p/10546956.html
时间: 2024-11-02 21:33:51