先上结果↓
话不多说,接下来就来看看代码全貌吧
//陈烦烦不说话
def read_data(data_path):
with open(data_path) as f:
data=f.read().split(',')
return data
S_student=read_data('work/stu5.txt')
M_student=read_data('work/stu6.txt')
class Student:
def __init__(self,name,dob,age,gender,spe,score=[]):
self.name=name
self.dob=dob
self.age=age
self.gen=gender
self.spe=spe
self.score=score
class Spostudent(Student):
def top3(self):
return sorted(abs(int(t)) for t in self.score)[0:3]
class Artstudent(Student):
def top3(self):
return sorted(abs(int(t)) for t in self.score)[-3:]
def Student_pr(stu):
print('姓名:%s,生日:%s,年龄:%s,性别:%s,分数:%s,特长分:%s'%(stu.name,stu.dob,stu.age,stu.gen,stu.top3(),stu.spe))
stu_5=Spostudent(S_student.pop(0),S_student.pop(0),S_student.pop(0),S_student.pop(0),S_student.pop(0),S_student)
stu_6=Artstudent(M_student.pop(0),M_student.pop(0),M_student.pop(0),M_student.pop(0),M_student.pop(0),M_student)
Student_pr(stu_5)
Student_pr(stu_6)
该代码是在解决这样一个问题:
定义Spostudent、Artstudent为Student的子类,在子类的属性里面新增了spe为特长分数。Spostudent包括的top3方法返回的是最低的3个得分(可重复),Artstudent包括top3方法返回的是最高的3个得分(可重复),最后使用多态的方式输出2个特长同学的姓名、生日、年龄、性别、分数、特长分。
对代码内容的一些讲解:
用到两个函数做封装,可以大大提高运行速度,也方便大家移植!
sorted(abs(int(t)) for t in self.score)[0:3]
这句话用到了两个python的内置函数,abs是将负数变为正数的,sorted是将数据排序
data=f.read().split(',')
这句话就是将文件内容以逗号为分隔符将文件分开,因为我读取的文件是这样子的,如果需要其他形式,如:空格。仅需改为split(' ')
本篇分享到此结束,如果有看不懂的地方欢迎给我留言!