python用类和方法重新编写学生管理系统,实现面向对象版的学生管理系统
时间: 2024-10-19 22:08:53 浏览: 10
在Python中,我们可以使用类(Class)和方法(Methods)来重构一个简单的学生管理系统。下面是一个基本的面向对象设计的例子:
```python
class Student:
def __init__(self, name, id, grade):
self.name = name
self.id = id
self.grade = grade
def display_info(self):
print(f"姓名:{self.name}, 学号:{self.id}, 年级:{self.grade}")
class Course:
def __init__(self, course_name, teacher):
self.course_name = course_name
self.teacher = teacher
def add_student(self, student):
student.enrolled_courses.append(self)
class EnrollmentSystem:
def __init__(self):
self.students = []
self.courses = []
def register_student(self, name, id, grade):
new_student = Student(name, id, grade)
self.students.append(new_student)
def enroll_in_course(self, student_id, course_name):
for student in self.students:
if student.id == student_id:
for course in self.courses:
if course.course_name == course_name:
course.add_student(student)
break
def view_student_courses(self, student_id):
for course in self.courses:
if student_id in [student.id for student in course.enrolled_students]:
print(f"{course.course_name} - 老师:{course.teacher}, 学生:{course.enrolled_students}")
# 使用示例
sys = EnrollmentSystem()
sys.register_student("张三", 1001, "高三")
sys.enroll_in_course(1001, "数学课")
sys.view_student_courses(1001)
```
在这个例子中,我们定义了`Student`类表示学生,包含姓名、学号和年级属性,以及显示信息的方法;`Course`类代表课程,包含名称和老师,并有添加学生的功能;`EnrollmentSystem`类作为整个系统的管理器,包含了注册学生、报名课程和查看学生课程的方法。
阅读全文