Python3 挑战实验 – 类和Collection

介绍

我们之前通过3个课程学习了 Python 的类,模块和Collection 模块的知识。这次我们通过一个简单的挑战实验来测试一下我们对之前知识点的掌握程度。

目标

改写我们在第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 终端中输入如下代码来获取

1
wget http://labfile.oss.aliyuncs.com/courses/790/student_teacher.py

要求

请把最终的student_teacher.py 代码文件放在 /home/shiyanlou/Code/ 路径下
根据命令行中的第一个参数 teacher 或者 student 来判断最终输出的格式。
命令行中第二个输入的参数是需要统计的字符串
举例:

提示语

  • import sys
  • collections 中的 Counter 子类
  • format() 以及 join

知识点

  • Collection 模块
  • 注意最终的打印形式

来源

实验楼团队

答案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# student_teacher.py
#!/usr/bin/env python3
import sys
from collections import Counter

class Person(object):
"""
返回具有给定名称的 Person 对象
"""

def __init__(self, grade):
self.grade = grade

def get_grade(self):
return self.grade


class Student(Person):
"""
返回 Student 对象,采用 grade 参数
"""

def __init__(self, grade):
Person.__init__(self, grade)

def get_grade(self):
counter = Counter(self.grade).most_common(4)
g_pass = g_fail = 0

for e in counter:
g, n = e
if g in ['A', 'B', 'C']:
g_pass += n
else:
g_fail += n

print('Pass: {}, Fail: {}'.format(g_pass, g_fail))

class Teacher(Person):
"""
返回 Teacher 对象,采用 grade 作为参数
"""
def __init__(self, grade):
Person.__init__(self, grade)

def get_grade(self):
counter = Counter(self.grade).most_common(4)
grade_list = []
for e in counter:
g, n = e
grade_list.append(g + ': '+ str(n))
print(', '.join(grade_list))

if __name__ == '__main__':
if sys.argv[1] == 'teacher':
teacher = Teacher(sys.argv[2])
teacher.get_grade()
else:
student = Student(sys.argv[2])
student.get_grade()