编写一个学生和教师数据输入和显示程序,学生数据有编号、姓名、班级和成绩,教师数据有编号、姓名、职称和部门。要求将编号、姓名输入和显示设计成一个类person,并作为学生数据操作类student和教师类数据操作类teacher的基类
时间: 2024-06-08 12:12:28 浏览: 228
下面是一个示例代码实现:
```python
class Person:
def __init__(self, id, name):
self.id = id
self.name = name
class Student(Person):
def __init__(self, id, name, cls, score):
super().__init__(id, name)
self.cls = cls
self.score = score
class Teacher(Person):
def __init__(self, id, name, title, department):
super().__init__(id, name)
self.title = title
self.department = department
class StudentData:
def __init__(self):
self.students = []
def add_student(self, student):
self.students.append(student)
def display_students(self):
for student in self.students:
print("ID: {}, Name: {}, Class: {}, Score: {}".format(student.id, student.name, student.cls, student.score))
class TeacherData:
def __init__(self):
self.teachers = []
def add_teacher(self, teacher):
self.teachers.append(teacher)
def display_teachers(self):
for teacher in self.teachers:
print("ID: {}, Name: {}, Title: {}, Department: {}".format(teacher.id, teacher.name, teacher.title, teacher.department))
```
在上面的代码中,我们先定义了一个基类 `Person`,它有编号和姓名两个属性。然后我们定义了两个子类 `Student` 和 `Teacher`,分别表示学生和教师,它们都继承了 `Person` 类,并且分别有自己的属性。最后我们定义了 `StudentData` 和 `TeacherData` 两个类,用于存储学生和教师的数据,并提供添加和显示数据的方法。
下面是一个使用示例:
```python
# 创建一些学生和教师对象
s1 = Student(1, "Alice", "Class 1", 90)
s2 = Student(2, "Bob", "Class 2", 85)
t1 = Teacher(1, "Bill", "Professor", "Department A")
t2 = Teacher(2, "Cindy", "Associate Professor", "Department B")
# 创建学生和教师数据操作对象
student_data = StudentData()
teacher_data = TeacherData()
# 添加学生和教师数据
student_data.add_student(s1)
student_data.add_student(s2)
teacher_data.add_teacher(t1)
teacher_data.add_teacher(t2)
# 显示学生和教师数据
print("Students:")
student_data.display_students()
print("Teachers:")
teacher_data.display_teachers()
```
输出结果如下:
```
Students:
ID: 1, Name: Alice, Class: Class 1, Score: 90
ID: 2, Name: Bob, Class: Class 2, Score: 85
Teachers:
ID: 1, Name: Bill, Title: Professor, Department: Department A
ID: 2, Name: Cindy, Title: Associate Professor, Department: Department B
```
阅读全文