标签:from color remove orm turn return port core container
设计一个班级类:属性:班级代号、所有学生
要求:实现向班级添加学生、删除学生、学生排序(指定条件)、查询学生信息(姓名、学号等)
解决思路,分为三大步。
一,定义学生类。属性有 名称,学号,年龄,分数
二,定义班级类 。 属性有班级名称,功能增加学生,删除学生,查询学生信息
三,创造学生得信息。用for循环创造学生信息,放入班级得字典和列表里。功能相当于是一个信息库
代码》
class Student :
def __init__(self,name,num,age,score):
self.xingming = name
self.num = num
self.age = age
self.score = score
def __str__(self):
return "name:{},num:{},age:{},score:{}".format(self.xingming,self.num,self.age,self.score)
class Class :
def __init__(self,name):
self.name = name
#创造空间存放学生信息
self.stu_list = []
self.stu_dict = {}
def add_stu(self,stu):
self.stu_list.append(stu)
self.stu_dict[stu.xingming] = stu
def del_stu(self,stu):
self.stu_list.remove(stu)
self.stu_dict.pop(stu.name)
def search_by_name(self,name):
return self.stu_dict.get(name)
def sort_by(self,key=None,reverse=False):
self.stu_list.sort(key=key,reverse=reverse)
def show_stu(self):
for s in self.stu_list:
print(s)
from random import randint ,uniform
c = Class("zz-jy-py1804")
for i in range(10):
name = "stu"+str(i+1)
num = i+100
age = randint(20,30)
score=int(uniform(50,100))
s=Student(name,num ,age,score)
c.add_stu(s)
c.sort_by(key=lambda s:s.score,reverse=True)
c.show_stu()
标签:from color remove orm turn return port core container
原文地址:https://www.cnblogs.com/chaojiyingxiong/p/9230910.html