用类的组合技术,设计一个基本信息类、一个学生类、一个教师类。基本信息类包括姓名、性别、手机号、班级;学生类包括姓名、性别、手机号、班级、数学、语文和英语等成绩;教师类包括姓名、性别、手机号、班级、专业、教龄等。以上三个类必须包含构造函数,其他成员函数自行设计。主函数中,分别生成一个学生类和教师类对象,并调用成员函数
时间: 2023-10-14 14:06:11 浏览: 66
学生类的构造函数
好的,我理解了你的问题,以下是代码示例:
```python
class BasicInfo:
def __init__(self, name, gender, phone_num, class_num):
self.name = name
self.gender = gender
self.phone_num = phone_num
self.class_num = class_num
class Student:
def __init__(self, name, gender, phone_num, class_num, math, chinese, english):
self.basic_info = BasicInfo(name, gender, phone_num, class_num)
self.math = math
self.chinese = chinese
self.english = english
def get_total_score(self):
return self.math+self.chinese+self.english
class Teacher:
def __init__(self, name, gender, phone_num, class_num, major, teaching_years):
self.basic_info = BasicInfo(name, gender, phone_num, class_num)
self.major = major
self.teaching_years = teaching_years
def get_teaching_experience(self):
return f"{self.basic_info.name} has {self.teaching_years} years of teaching experience in {self.major}."
# 创建一个学生对象
student = Student("小明", "男", "123456789", "一班", 90, 85, 92)
print(f"{student.basic_info.name}的总成绩是{student.get_total_score()}分。")
# 创建一个教师对象
teacher = Teacher("张老师", "女", "987654321", "二班", "英语", 10)
print(teacher.get_teaching_experience())
```
输出结果如下:
```
小明的总成绩是267分。
张老师 has 10 years of teaching experience in 英语.
```
在上述代码中,我们使用了类的组合技术,将基本信息类作为学生类和教师类的成员变量,这样可以避免代码冗余并提高代码复用性。同时,我们也为每个类设计了构造函数,并添加了一些自定义的成员函数,以满足不同的需求。在主函数中,我们分别创建了一个学生对象和一个教师对象,并调用了它们的成员函数。
阅读全文