参考学生图书管理的代码,将学生管理代码重构为面向对象的代码
时间: 2024-03-07 14:49:49 浏览: 49
学生管理代码设计
好的,我会根据您的要求,将学生管理代码重构为面向对象的代码。
首先,我们需要定义一个学生类,包含学生的基本信息和操作方法:
```python
class Student:
def __init__(self, name, id, gender, major):
self.name = name
self.id = id
self.gender = gender
self.major = major
def get_name(self):
return self.name
def get_id(self):
return self.id
def get_gender(self):
return self.gender
def get_major(self):
return self.major
def set_name(self, name):
self.name = name
def set_id(self, id):
self.id = id
def set_gender(self, gender):
self.gender = gender
def set_major(self, major):
self.major = major
def __str__(self):
return f"Name: {self.name}, ID: {self.id}, Gender: {self.gender}, Major: {self.major}"
```
接下来,我们可以定义一个学生管理类,包含对学生列表的增删改查操作:
```python
class StudentManager:
def __init__(self):
self.student_list = []
def add_student(self, name, id, gender, major):
student = Student(name, id, gender, major)
self.student_list.append(student)
def remove_student(self, id):
for student in self.student_list:
if student.get_id() == id:
self.student_list.remove(student)
print(f"Successfully removed student with ID {id}")
return
print(f"No student found with ID {id}")
def update_student(self, id, name=None, gender=None, major=None):
for student in self.student_list:
if student.get_id() == id:
if name:
student.set_name(name)
if gender:
student.set_gender(gender)
if major:
student.set_major(major)
print(f"Successfully updated student with ID {id}")
return
print(f"No student found with ID {id}")
def search_student(self, id):
for student in self.student_list:
if student.get_id() == id:
print(student)
return
print(f"No student found with ID {id}")
def display_all_students(self):
for student in self.student_list:
print(student)
```
现在,我们可以创建一个学生管理对象,通过调用其方法来操作学生列表:
```python
student_manager = StudentManager()
student_manager.add_student("Tom", "1001", "Male", "Computer Science")
student_manager.add_student("Jerry", "1002", "Female", "Mathematics")
student_manager.display_all_students()
student_manager.remove_student("1002")
student_manager.update_student("1001", name="John", major="Physics")
student_manager.search_student("1001")
```
重构后的代码更加清晰、简洁,也更易于扩展和维护。
阅读全文