Day29.继承实现
1.继承实现_示范1创建学生类和老师类,双类中存在冗余代码
# 示范1:类与类之前存在冗余问题 class Student: school = 'OLDBOY' def __init__(self, name, age, sex): self.name = name self.age = age self.sex = sex def chooser_course(self): print('%s 正向选课' % self.name) class Teacher: school = 'OLDBOY' def __init__(self, name, age, sex, salary, level): self.name = name self.age = age self.sex = sex self.salary = salary self.sex = sex def score(self): print('老师 %s 正在给学生打分' % self.name)
2.继承实现_示范2学生类继承共有数据类
# 示范2:基于继承解决类与类之间的冗余问题 class OldboyPeople: school = 'OLDBOY' # 空对象,'egon', 18, 'male', 3000, 10 def __init__(self, name, age, sex): self.name = name self.age = age self.sex = sex # 然后继承共同部分的`class 类名(OldboyPeople)` class Student(OldboyPeople): def chooser_course(self): print('学生%s 正向选课' % self.name) stu_obj = Student('lili', 18, 'femal') print('Student类,基于继承解决类与类之间的冗余问题'.center(40, '-')) print(stu_obj.__dict__) print(stu_obj.school) stu_obj.chooser_course()
3.继承实现_示范2老师类继承共有数据类,非共有数据在老师类中的__init__下新增定义
# 示范2:基于继承解决类与类之间的冗余问题 class OldboyPeople: school = 'OLDBOY' # 空对象,'egon', 18, 'male', 3000, 10 def __init__(self, name, age, sex): self.name = name self.age = age self.sex = sex # 然后继承共同部分的`class 类名(OldboyPeople)` class Teacher(OldboyPeople): def __init__(self, name, age, sex, salary, level): # 有三个参数和父类OldboyPeople相同,相同的部分可以指名道姓的和父类OldboyPeople去要__init__ # 不同部分在Teacher类下的__init__中重新定义 OldboyPeople.__init__(self, name, age, sex) # 等同于在Teacher类中__init__写 # self.name = name # self.age = age # self.sex = sex self.salary = salary self.level = level def score(self): print('老师 %s 正在给学生打分' % self.name) tea_obj = Teacher('egon', 18, 'male', 3000, 10) print('Teacher类,相同参数部分继承父类,不同参数部分在Teacher类下添加'.center(60, '-')) print(tea_obj.__dict__) tea_obj.score()