class A: pass class B(A): pass
继承是一种‘是’的关系: 人类、猪类、狗类都继承动物类,于是他们都是动物
解决代码重用问题? 解决的是:什么是什么的问题-》继承
若是子类衍生出的新的属性与父类的某个属性名字相同, 那么再调用子类的这个属性,就以子类本身这里的为准了
class A: def test(self): print("This is A !") class B(A): def test(self): A.test(B) #super().test() #若是在python2中super须要跟参数:super(B,self).test() print("This is B !") b=B() b.test()
老师有课程python
学生有成绩函数
学生有课程code
学校有老师继承
学校有学生接口
class Course: def __init__(self,name,price,period): self.name=name self.price=price self.period=period class Teacher: def __init__(name,course): self.name=name self.course=course class Student: def __init__(name,course): self.name=name self.course=course python=Course('python',15800,'7m') t1=Teacher('egon',python) s1=Student('alex',python) print(s1.course.name) print(s1.course.period)
class Animal: def run(self): raise AttributeError('子类必须实现这个方法') class People(Animal): def run(self): print('人正在走') class Pig(Animal): def run(self): print('pig is walking') class Dog(Animal): def run(self): print('dog is running') peo1=People() pig1=Pig() d1=Dog() peo1.run() pig1.run() d1.run()
def func(obj): obj.run() func(peo1) func(pig1) func(d1) 多态性依赖于: 1.继承 2. 多态性:定义统一的接口, def func(obj): #obj这个参数没有类型限制,能够传入不一样类型的值 obj.run() #调用的逻辑都同样,执行的结果却不同 func(peo1) func(pig1) func(d1)
class A(object): def test(self): print('from A') pass class B(A): def test(self): print('from B') pass class C(A): def test(self): print('from C') pass class D(B): def test(self): print('from D') pass class E(C): def test(self): print('from E') pass class F(D,E): def test(self): print('from F') pass f1=F() f1.test() print(F.__mro__) #会返回继承顺序的一个列表 print(F.mro()) #同上 #广度优先:F->D->B->E->C->A->object 会找到倒数第二层,再找其余分支,所有分支找完再找最底层,2
class A: def test(self): print('from A') pass class B(A): def test(self): print('from B') pass class C(A): def test(self): print('from C') pass class D(B): def test(self): print('from D') pass class E(C): def test(self): print('from E') pass class F(D,E): def test(self): print('from F') pass f1=F() f1.test() #深度优先 F->D->B->A->E->C 经典类中没有mro()方法 优先找完一整条路,再找另一条。