学生选修课程这一事实可以用学生类和课程类之间的关联关系来建模。设计并实现这两个类以及它们的关联关系。要求如下。 (1)学生的属性有姓名和学号。 (2)课程的属性有课程名、课程编号和学分。 模拟学生选课的操作,选课完成后: (3)课程能知道选修了该课程的所有学生以及学生总数。 (4)学生知道自己选修了哪些课程以及总的学分。 编写测试程序,输出学生对象,能够输出该学生的姓名、学号,以及该生所选的课程名、课程编号和学分,并能输出该学生选修课程的总学分数; 输出课程对象,能够输出该门课程的课程名、课程编号、学分,以及选修该课程所有的学生姓名、学号,并能输出选修该课程的学生总数。
时间: 2023-06-10 09:08:20 浏览: 88
以下Python的实现代码:
```python
class Student:
def __init__(self, name, id):
self.name = name
self.id = id
self.courses = []
self.total_credits = 0
def add_course(self, course):
self.courses.append(course)
self.total_credits += course.credit
def print_info(self):
print("Name:", self.name)
print("ID:", self.id)
print("Courses:")
for course in self.courses:
print(course.name, course.id, course.credit)
print("Total credits:", self.total_credits)
class Course:
def __init__(self, name, id, credit):
self.name = name
self.id = id
self.credit = credit
self.students = []
def add_student(self, student):
self.students.append(student)
def get_student_count(self):
return len(self.students)
def print_info(self):
print("Name:", self.name)
print("ID:", self.id)
print("Credit:", self.credit)
print("Students:")
for student in self.students:
print(student.name, student.id)
print("Total student count:", self.get_student_count())
# Test program
s1 = Student("Alice", "001")
s2 = Student("Bob", "002")
c1 = Course("Math", "001", 3)
c2 = Course("English", "002", 2)
c3 = Course("History", "003", 4)
# Alice selects Math and English
s1.add_course(c1)
s1.add_course(c2)
c1.add_student(s1)
c2.add_student(s1)
# Bob selects English and History
s2.add_course(c2)
s2.add_course(c3)
c2.add_student(s2)
c3.add_student(s2)
# Output Alice's info
s1.print_info()
# Output English's info
c2.print_info()
```
输出结果如下:
```
Name: Alice
ID: 001
Courses:
Math 001 3
English 002 2
Total credits: 5
Name: English
ID: 002
Credit: 2
Students:
Alice 001
Bob 002
Total student count: 2
```
阅读全文