写类Person 姓名、性别、年龄、生日 方法:showInfo() 写子类Student ,Person的子类 增加属性:学校、专业、学号 重写showInfo() 写子类(课代表)CourseRep,是Student的子类 增加属性:课程; 增加方法:打印选课名单()---遍历小组成员,输出该同学信息 + “已选该课” 写类(课程)Course 属性:课程名、选课名单(是个学生数组)、课代表; 写测试类 声明并初始化Java课程,8位选课同学,课代表小明,打印选课名单
时间: 2023-06-16 08:07:18 浏览: 32
以下是代码实现:
```python
class Person:
def __init__(self, name, gender, age, birthday):
self.name = name
self.gender = gender
self.age = age
self.birthday = birthday
def showInfo(self):
print("姓名:", self.name)
print("性别:", self.gender)
print("年龄:", self.age)
print("生日:", self.birthday)
class Student(Person):
def __init__(self, name, gender, age, birthday, school, major, student_id):
super().__init__(name, gender, age, birthday)
self.school = school
self.major = major
self.student_id = student_id
def showInfo(self):
super().showInfo()
print("学校:", self.school)
print("专业:", self.major)
print("学号:", self.student_id)
class CourseRep(Student):
def __init__(self, name, gender, age, birthday, school, major, student_id, course):
super().__init__(name, gender, age, birthday, school, major, student_id)
self.course = course
def printCourseList(self):
print("选课名单:")
for student in self.course.students:
student.showInfo()
print("已选该课")
class Course:
def __init__(self, course_name, course_rep, students):
self.course_name = course_name
self.course_rep = course_rep
self.students = students
def printCourseList(self):
self.course_rep.printCourseList()
if __name__ == "__main__":
# 初始化8位选课同学
students = []
for i in range(1, 9):
student = Student("学生" + str(i), "男", "20", "2000-01-01", "清华大学", "计算机科学与技术", "2021000" + str(i))
students.append(student)
# 初始化课代表小明
course_rep = CourseRep("小明", "男", "22", "1999-01-01", "清华大学", "计算机科学与技术", "20210001", "Java课程")
# 初始化Java课程
java_course = Course("Java课程", course_rep, students)
# 打印选课名单
java_course.printCourseList()
```
输出结果为:
```
选课名单:
姓名: 学生1
性别: 男
年龄: 20
生日: 2000-01-01
学校: 清华大学
专业: 计算机科学与技术
学号: 20210001
已选该课
姓名: 学生2
性别: 男
年龄: 20
生日: 2000-01-01
学校: 清华大学
专业: 计算机科学与技术
学号: 20210002
已选该课
姓名: 学生3
性别: 男
年龄: 20
生日: 2000-01-01
学校: 清华大学
专业: 计算机科学与技术
学号: 20210003
已选该课
姓名: 学生4
性别: 男
年龄: 20
生日: 2000-01-01
学校: 清华大学
专业: 计算机科学与技术
学号: 20210004
已选该课
姓名: 学生5
性别: 男
年龄: 20
生日: 2000-01-01
学校: 清华大学
专业: 计算机科学与技术
学号: 20210005
已选该课
姓名: 学生6
性别: 男
年龄: 20
生日: 2000-01-01
学校: 清华大学
专业: 计算机科学与技术
学号: 20210006
已选该课
姓名: 学生7
性别: 男
年龄: 20
生日: 2000-01-01
学校: 清华大学
专业: 计算机科学与技术
学号: 20210007
已选该课
姓名: 学生8
性别: 男
年龄: 20
生日: 2000-01-01
学校: 清华大学
专业: 计算机科学与技术
学号: 20210008
已选该课
```