1.继承应用
类是解决对象之间的冗余问题,而类与类之间的冗余问题用用继承(is-a狗是动物)和组合(组合使用stu.couse):
例子1
(1)原始代码
class student:
school='虹桥校区' def __init__(self,name,age,gender): self.name=name self.age=age self.gender=gender def choose(self): print('%s选课成功'%self.name) stu1=student('egon',18,'male') stu2=student('lxx',38,'male') stu3=student('lili',20,'female') class teacher: school='虹桥校区' def __init__(self,name,age,gender,level): self.name=name self.age=age self.gender=gender self.level=level def score(self): print('%s正在为学生打分'%self.name) teacher1=teacher('egon',18,'male',10) teacher2=teacher('lxx',38,'male',3)
(2)继承和派生后
class people: <父类> school = '虹桥校区' def __init__(self,name,age,gender): self.name=name self.age=age self.gender=gender
class student(people): <子类+继承> def choose(self): print('%s选课成功'%self.name) stu1=student('egon',18,'male') stu2=student('lxx',38,'male') stu3=student('lili',20,'female') class teacher(people): <子类+派生>
def __init__(self,name,age,gender,level):
people.__init__(self,name,age,gender) #调用函数
或 super(teacher,self).__init__(name,age,gender) #supper
(supper()返回的是一个特殊的对象,该对象会参考发起属性查找那个类的MRO列表,然后继续往后找)
self.level=level
def score(self):
print('%s正在为学生打分'%self.name)
teacher1=teacher('egon',18,'male',10)
teacher2=teacher('lxx',38,'male',3)
print(stu1.name)
print(teacher1.__dict__)
2.继承实现的原理
如果继承关系为非菱形结构,则会按照先找B这一条分支,然后再找C这一条分支,最后找D这一条分支的顺序直到找到我们想要的属性(棍子查找,新式类最后找object)
(新式类:一直找,最好再找大脑袋,经典类一支就找到大脑袋)
如果继承关系为菱形结构,那么属性的查找方式有两种,分别是:深度优先和广度优先
3.supper
supper()返回的是一个特殊的对象,该对象会参考发起属性查找那个类的MRO列表,然后继续往后找
class a: def test(self): print('from a') super().test() class b: def test(self): print('from b') class c(a,b): pass obj=c() obj.test()
结果是:
from a
from b
4.多继承的代码规范(mixins机制)
继承表达是一个is-a的关系
class Vehicle: #都是交通工具 pass class FlyableMixin #都有飞行能力 def fly(self): print('flying') class CivilAircraft(FlyableMixin,Vehicle): pass class Helicopter(FlyableMixin,Vehicle): pass class Car(Vehicle): pass
5.组合
class people: school='上海校区' def __init__(self,name,age,gender): self.name=name self.age=age self.gender=gender class student(people): def choose(self): print('%s选课功能'%self.name) class teacher(people): def __init__(self,name,age,gender,level): people.__init__(self,name,age,gender) self.level=level def score(self): print('%s正在为学生打分'%self.name) class couse: def __init__(self,name,price,period): self.name=name self.price=price self.period=period def tell(self): print('课程信息<%s:%s:%s>'%(self.name,self.price,self.period)) python=couse('python全栈开发',19980,'6m') linux=couse('linux',19000,'5m') stu1=student('egon',18,'male') stu2=student('tom',20,'female') tea1=teacher('egon',22,'male',10) tea2=teacher('lili',20,'male',3) stu1.couse=python #所谓的组合就是指这里的组合使用的 stu1.couse.tell() #结果是:课程信息<python全栈开发:19980:6m>