继承
1.什么是继承?
继承一种新建类的一种方法,在python中支持一个儿子有多个爹
新建的类称之为子类或者派生类,父类又可以称之为基类或者超类
子类会‘遗传’父类的属性
2.为什么要用继承
减少代码冗余
3.继承是类与类之间的关系,寻找这种关系需要先抽象再继承
抽象即抽取类似或者说比较像的部分
继承是基于抽象的结果,通过编程语言去实现它,肯定要先经历抽象这个过程
父类与子类的使用
class OldboyPeopler: #父类 school='oldboy' def __init__(self,name,age,sex) self.name=name self.age=age self.sex=sex class OldboyTeacher(OldboyPeopler): #子类 def change_acore(self): print('teacher %s is changing score'%self.name) class Oldboystudent(OldboyPeopler): #子类 def choose(self) print('student %s choose course'%self.name) tea1=OldboyTeacher('egon',18,'male') stu1=Oldboystudent('gao',18,'male') print(tea1.name,tea1.age,tea1.sex) #egon 18 male
print(Oldboystudent.__bases__) #查看继承用(__bases__) (<class '__main__.OldboyPeople'>,)
基于继承再看属性查找
class Foo: def f1(self): print('foo.f1') def f2(self): print('foo.f2') self.f1() class Bar(Foo): def f1(self): print('Bar.fi') b=Bar() b.f2() #Foo.f2 , Bar.f1 b先在自己的对象查找,没有就去自己的类查找,没有就去自己的父类查找。没有就近查找的说法。
派生:子类定义自己新的属性,如果与父类同名,以子类自己的为准
class OldboyPeopler: school='oldboy' def __init__(self,name,age,sex) self.name=name self.age=age self.sex=sex def f1(self): print('爹的f1') class OldboyTeacher(OldboyPeopler): def change_acore(self): print('teacher %s is changing score'%self.name) def f1(self): print('儿子的f1') tea1=OldboyTeacher('gao',18,'male') tea1.f1() #儿子的f1
在子类派生出新方法中重用父类的功能
方式一:指名道姓的调用(其实与继承没有什么关系)
OldboyPeople.__init__(self,name,age,sex)
class OldboyPeople: school = 'oldboy' def __init__(self, name, age, sex): self.name = name self.age = age self.sex = sex class OldboyTeacher(OldboyPeople): def __init__(self,name,age,sex,level,salary): OldboyPeople.__init__(self,name,age,sex) self.level=level self.salary=salary def change_score(self): print('teacher %s is changing score' %self.name) tea1 = OldboyTeacher('egon', 18, 'male',9,3.1) print(tea1.name,tea1.age,tea1.sex,tea1.level,tea1.salary) #egon 18 male 9 3.1
方式二:super()调用(严格依赖于继承)
super()的返回值是一个特殊的对象,该对象专门用来调用父类中的属性
了解点:在python2中,需要super(自己的类名,self)
super().__init__(name,age,sex)
经典类与新式类
1.新式类:
继承object的类,以及该类的子类,都是新式类
在python3中,如果一个类没有指定继承的父类,默认就继承object
所以说python3中所以的类都是新式类
2.经典类:(只有在python2中才区分经典类和新式类):
没有继承object的类,以及该类的子类,都是经典类
class Foo(object): pass class Bar(Foo): pass print(Bar.__bases__) #(<class '__main__.Foo'>,)
在多继承的背景下的属性查找
在菱形继承的背景下,查找属性
1.经典类:深度优先
2.新式类:广度优先
super()会严格按照mro列表从当前查找到的位置继续往后查找
class A: def test(self): print('A.test') super().f1() class B: def f1(self): print('from B') class C(A,B): pass c=C() print(C.mro()) #C->A->B->object c.test() # A.test,from B