改写我们在第11节类这个模块当中 2.3 继承 部分的 student_teacher.py 脚本,在Person()类中增添函数get_grade()。对于教师类,该函数可以自动统计出老师班上学生的得分情况并按照频率的高低以A: X, B: X, C: X, D: X 的形式打印出来。对于学生类,该函数则可以以Pass: X, Fail: X 来统计自己的成绩情况(A,B,C 为 Pass, 如果得了 D 就认为是 Fail)。
student_teacher.py 文件可以通过在Xfce 终端中输入如下代码来获取
wget http://labfile.oss.aliyuncs.com/courses/790/student_teacher.py
要求
#!/usr/bin/env python3
import sys
from collections import Counter
class Person(object):
"""
返回具有给定名称的 Person 对象
"""
def __init__(self, name, grade):
self.name = name
self.grade = grade
def get_details(self):
"""
返回包含人名的字符串
"""
return self.name
def get_grade(self):
return self.grade
class Student(Person):
"""
返回 Student 对象,采用 name, branch, year, grade 4 个参数
"""
def __init__(self, name, branch, year, grade):
Person.__init__(self, name, grade)
self.branch = branch
self.year = year
def get_details(self):
"""
返回包含学生具体信息的字符串
"""
return "{} studies {} and is in {} year.".format(self.name, self.branch, self.year)
def get_grade(self):
c = Counter(self.grade)
return "Pass: {}, Fail: {}".format(c['A']+c['B']+c['C'], c['D'])
class Teacher(Person):
"""
返回 Teacher 对象,采用字符串列表作为参数
"""
def __init__(self, name, papers, grade):
Person.__init__(self, name, grade)
self.papers = papers
def get_details(self):
return "{} teaches {}".format(self.name, ','.join(self.papers))
def get_grade(self):
c = Counter(self.grade).most_common()
s = ["{}: {}".format(x,y) for x,y in c]
return ','.join(s)
if __name__ == '__main__':
if len(sys.argv) != 3:
print("Wrong Parameter!")
sys.exit(1)
if(sys.argv[1]=="student"):
student = Student("Kane","CSE", 2016, sys.argv[2])
print(student.get_grade())
else:
teacher = Teacher('jjj',['C++'], sys.argv[2])
print(teacher.get_grade())