1、定义一个父类Student和两个子类LevelSt和PassSt,在父类中定义2个实例变量,使子类继承父类的所有属性和方法,并各自定义根据成绩计算等级和判断是否通过的方法;同时,将代码存储在student.py文件中
2、显示有LevelSt和PassSt类对象构成的学生成绩列表,以及所有学生名字和成绩,并按字典排序
class Student: def __init__(self,name,grade): self.name = name self.grade = grade def setName(self,name): self.name = name def setGrade(self,grade): self.grade = grade def getName(self): return self.name def show(self): print('%s\t %s'%(self.name,self.calcLevel())) class LevelSt(Student): def calcLevel(self): if self.grade>=90: return 'A' elif self.grade>=80: return 'B' elif self.grade>=70: return 'C' elif self.grade>=60: return 'D' else: return 'E' class PassSt(Student): def calcLevel(self): if self.grade>=60: return '通过' else: return '不通过' def list_St(): listOfSt=[] is_continue = 'Y' while is_continue in ['Y','y','YES','yes']: name = input('请输入名字:') grade = float(input('请输入成绩:')) choice = input('请选择(L or P):') if choice.upper() == 'L': s = LevelSt(name,grade) else: s = PassSt(name,grade) listOfSt.append(s) is_continue = input('继续?(y/n):') return listOfSt def display(listOfSt): print('\n姓名 \t 等级') listOfSt.sort(key = lambda x:x.getName()) for each in listOfSt: each.show() def main(): listOfSt = list_St() display(listOfSt) if __name__ == '__main__': main()
运行结果: