题目描述
1、建立如下的类继承结构:
1)定义一个人员类CPeople,其属性(保护类型)有:姓名、性别、年龄;
2)从CPeople类派生出学生类CStudent,添加属性:学号和入学成绩;
3)从CPeople类再派生出教师类CTeacher,添加属性:职务、部门;
4)从CStudent和CTeacher类共同派生出在职研究生类CGradOnWork,添加属性:研究方向、导师;
2、分别定义以上类的构造函数、输出函数print及其他函数(如需要)。
3、在主函数中定义各种类的对象,并测试之。
输入
第一行:姓名性别年龄
第二行:学号成绩
第三行:职务部门
第四行:研究方向导师
输出
第一行:People:
第二行及以后各行:格式见Sample
输入样例1
wang-li m 23 2012100365 92.5 assistant computer robot zhao-jun
输出样例1
People: Name: wang-li Sex: m Age: 23
Student: Name: wang-li Sex: m Age: 23 No.: 2012100365 Score: 92.5
Teacher: Name: wang-li Sex: m Age: 23 Position: assistant Department: computer
GradOnWork: Name: wang-li Sex: m Age: 23 No.: 2012100365 Score: 92.5 Position: assistant Department: computer Direction: robot Tutor: zhao-jun
思路分析
这道题涉及到类的多重继承,CPeople作为基类派生出CStudent和CTeacher,然后由这两个子类共同派生出CGradOnWork类。
Python的多重继承没有那么复杂,它很聪明,不需要虚函数,它自己会知道要调用哪个成员函数。
而且,对于多重继承来说,两个父类具有相同的属性,这个孙类也只会继承一个。
AC代码
代码语言:javascript复制class CPeolpe:
def __init__(self,name,sex,age):
self.name,self.sex,self.age=name,sex,age
def print(self):
print('People:nName: %snSex: %snAge: %dn'%(self.name,self.sex,self.age))
class CStudent(CPeolpe):
def __init__(self,name,sex,age,idnum,score):
self.name,self.sex,self.age,self.idnum,self.score=name,sex,age,idnum,score
def print(self):
print('Student:nName: %snSex: %snAge: %dnNo.: %snScore: %.1fn'%(self.name,self.sex,self.age,self.idnum,self.score))
class CTeacher(CPeolpe):
def __init__(self,name,sex,age,work,department):
self.name,self.sex,self.age,self.work,self.department=name,sex,age,work,department
def print(self):
print('Teacher:nName: %snSex: %snAge: %dnPosition: %snDpartment: %sn'%(self.name,self.sex,self.age,self.work,self.department))
class CGradOnWork(CStudent,CTeacher):
def __init__(self,name,sex,age,idnum,score,work,department,direction,tutor):
self.name,self.sex,self.age,self.idnum,self.score,self.work,self.department,self.direction,self.tutor=name,sex,age,idnum,score,work,department,direction,tutor
def print(self):
print('GradOnWork:nName: %snSex: %snAge: %dnNo.: %snScore: %.1fnPosition: %snDepartment: %snDirection: %snTutor: %sn'%(self.name,self.sex,self.age,self.idnum,self.score,self.work,self.department,self.direction,self.tutor))
name,sex,age=input().split()
idnum,score=input().split()
work,department=input().split()
direction,tutor=input().split()
age=int(age)
score=float(score)
people=CPeolpe(name,sex,age)
people.print()
student=CStudent(name,sex,age,idnum,score)
student.print()
teacher=CTeacher(name,sex,age,work,department)
teacher.print()
outman=CGradOnWork(name,sex,age,idnum,score,work,department,direction,tutor)
outman.print()