编写一个学生和教师的数据输入和显示程序。学生的数据有编号、姓名、性别、年龄、系别和成绩,教师数据有编号、姓名、性别、年龄、职称和部门。要求将编号、姓名、性别、年龄的输入和显示设计成一个类Person,并做为学生类Student和教师类Teacher的基类。
时间: 2023-07-10 15:17:45 浏览: 87
好的,我可以帮你编写这个程序。以下是代码实现:
```python
class Person:
def __init__(self, id, name, gender, age):
self.id = id
self.name = name
self.gender = gender
self.age = age
def display(self):
print("ID:", self.id)
print("Name:", self.name)
print("Gender:", self.gender)
print("Age:", self.age)
class Student(Person):
def __init__(self, id, name, gender, age, department, score):
super().__init__(id, name, gender, age)
self.department = department
self.score = score
def display(self):
super().display()
print("Department:", self.department)
print("Score:", self.score)
class Teacher(Person):
def __init__(self, id, name, gender, age, title, department):
super().__init__(id, name, gender, age)
self.title = title
self.department = department
def display(self):
super().display()
print("Title:", self.title)
print("Department:", self.department)
# Test code
student = Student(1, "Tom", "Male", 20, "Computer Science", 90)
teacher = Teacher(2, "Mary", "Female", 35, "Professor", "Computer Science")
student.display()
print()
teacher.display()
```
运行结果:
```
ID: 1
Name: Tom
Gender: Male
Age: 20
Department: Computer Science
Score: 90
ID: 2
Name: Mary
Gender: Female
Age: 35
Title: Professor
Department: Computer Science
```
以上代码定义了一个名为Person的基类,它包含了编号、姓名、性别和年龄等公共属性和方法。然后,我们定义了Student类和Teacher类,它们都继承自Person类,并添加了各自的属性和方法。
在以上代码中,我们使用了Python的super()函数来调用父类的构造函数和display()方法,以避免代码重复。最后,我们创建了一个Student对象和一个Teacher对象,并分别调用它们的display()方法来显示它们的属性。
阅读全文