设计学生类Student和学生管理类StudentManger。
时间: 2023-12-14 11:36:09 浏览: 65
以下是一个简单的示例:
```python
class Student:
def __init__(self, name, age, gender, id):
self.name = name
self.age = age
self.gender = gender
self.id = id
def __str__(self):
return f"{self.name} ({self.age}, {self.gender}) - ID: {self.id}"
class StudentManager:
def __init__(self):
self.students = []
def add_student(self, student):
self.students.append(student)
print(f"Student {student.name} added.")
def remove_student(self, student_id):
for student in self.students:
if student.id == student_id:
self.students.remove(student)
print(f"Student {student.name} removed.")
return
print(f"Student with ID {student_id} not found.")
def display_students(self):
print("List of students:")
for student in self.students:
print(student)
```
在上面的代码中,`Student` 类表示学生,包含姓名、年龄、性别和 ID 属性。 `StudentManager` 类用于管理学生,可以添加、删除和显示学生。
要使用这些类,可以创建一个 `StudentManager` 对象,然后调用其方法,如下所示:
```python
manager = StudentManager()
s1 = Student("Alice", 18, "Female", 1001)
manager.add_student(s1)
s2 = Student("Bob", 19, "Male", 1002)
manager.add_student(s2)
manager.display_students()
manager.remove_student(1001)
manager.display_students()
```
以上代码将会输出:
```
Student Alice added.
Student Bob added.
List of students:
Alice (18, Female) - ID: 1001
Bob (19, Male) - ID: 1002
Student Alice removed.
List of students:
Bob (19, Male) - ID: 1002
```
阅读全文