编写程序,创建 People 类,该类中包含三种属性:姓名、性别、年龄以及针对每个属性的 get 和 set 方法。创建 Student 类,继承自 People 类,添加额外三个属性:学号、班级和数量统计。 创建 Teacher 类,继承自 People 类,添加额外三个属性:工号、学院和数量统计。要求在 Student 类 和 Teacher 类中分别实现 printInfo 方法,该方法打印对象的多有属性信息。
时间: 2024-03-08 12:50:21 浏览: 240
好的,以下是 Python 代码实现:
```python
class People:
def __init__(self, name, gender, age):
self.name = name
self.gender = gender
self.age = age
def get_name(self):
return self.name
def set_name(self, name):
self.name = name
def get_gender(self):
return self.gender
def set_gender(self, gender):
self.gender = gender
def get_age(self):
return self.age
def set_age(self, age):
self.age = age
class Student(People):
count = 0
def __init__(self, name, gender, age, student_id, class_name):
super().__init__(name, gender, age)
self.student_id = student_id
self.class_name = class_name
Student.count += 1
def print_info(self):
print("Name:", self.name)
print("Gender:", self.gender)
print("Age:", self.age)
print("Student ID:", self.student_id)
print("Class Name:", self.class_name)
class Teacher(People):
count = 0
def __init__(self, name, gender, age, teacher_id, college):
super().__init__(name, gender, age)
self.teacher_id = teacher_id
self.college = college
Teacher.count += 1
def print_info(self):
print("Name:", self.name)
print("Gender:", self.gender)
print("Age:", self.age)
print("Teacher ID:", self.teacher_id)
print("College:", self.college)
```
其中,`People` 类是基类,包含三个属性和对应的 `get` 和 `set` 方法。`Student` 类继承自 `People` 类,添加了学号、班级属性和数量统计属性 `count`,并实现了 `print_info` 方法。`Teacher` 类同理。
下面是使用示例:
```python
# 创建两个学生对象
s1 = Student("Tom", "male", 18, "001", "Class A")
s2 = Student("Lucy", "female", 17, "002", "Class B")
# 调用 print_info 方法打印信息
s1.print_info()
s2.print_info()
# 创建两个教师对象
t1 = Teacher("John", "male", 35, "1001", "College of Science")
t2 = Teacher("Mary", "female", 28, "1002", "College of Arts")
# 调用 print_info 方法打印信息
t1.print_info()
t2.print_info()
# 打印学生和教师数量统计
print("Number of students:", Student.count)
print("Number of teachers:", Teacher.count)
```
输出结果如下:
```
Name: Tom
Gender: male
Age: 18
Student ID: 001
Class Name: Class A
Name: Lucy
Gender: female
Age: 17
Student ID: 002
Class Name: Class B
Name: John
Gender: male
Age: 35
Teacher ID: 1001
College: College of Science
Name: Mary
Gender: female
Age: 28
Teacher ID: 1002
College: College of Arts
Number of students: 2
Number of teachers: 2
```
阅读全文