继承的作用
可以利用继承来减少代码冗余
class Person:
school='aaaa'
def __init__(self,name,age,):
self.name=name
self.age=age
![](https://img2018.cnblogs.com/blog/1751692/201908/1751692-20190827184612437-657864509.png)
class Teacher(Person):
pass
class Student(Person):
pass
#类实例化会自动调用__init__如果类中没有,去父类中找
# stu1=Student() #报错,因为父类中必须传两个参数
stu1=Student('nick',18)
print(stu1.school)
多层继承
class A:
a="AAAA"
class B(A):
a="BBB"
class C(B):
# a="CCC"
pass
class D(C):
# a = "DDD"
pass
d=D()
print(d.a)
多继承
class A:
# a="AAAA"
pass
class B:
# a="BBB"
pass
class C:
a="CCC"
pass
class D(A,B,C):
# a = "DDD"
pass
d=D()
print(d.a)
继承的菱形问题
新式类和经典类的查找顺序是不一样的
新式类的查找属性:广度优先
经典类:深度优先
# class G(object):
# a = "GGG"
# pass
# class F(G):
# # a = "FFF"
# pass
# class E(G):
# # a = "EEE"
# pass
# class D(G):
# # a = "DDD"
# pass
# class C(F):
# # a="CCC"
# pass
# class B(E):
# # a="BBB"
# pass
# class A(B,C,D):
# # a="AAAA"
# pass
#
# a=A()
# print(a.a)
class G(object):
a = "GGG"
pass
class F(G):
# a = "FFF"
pass
class E(G):
# a = "EEE"
pass
class D(G):
# a = "DDD"
pass
class C(F):
# a="CCC"
pass
class B(E):
# a="BBB"
pass
class A(B,C,D):
# a="AAAA"
pass
a=A()
print(a.a)
#mro 列表,继承顺序查找列表(只在新式类中有)1
print(A.mro())
print(A.__mro__)
GGG
[<class 'main.A'>, <class 'main.B'>, <class 'main.E'>, <class 'main.C'>, <class 'main.F'>, <class 'main.D'>, <class 'main.G'>, <class 'object'>]
(<class 'main.A'>, <class 'main.B'>, <class 'main.E'>, <class 'main.C'>, <class 'main.F'>, <class 'main.D'>, <class 'main.G'>, <class 'object'>)
继承的菱形问题(显示的都继承一个类,不是object类):新式类和经典类的查找顺序是不一样的
新式类(py3中全是新式类):广度优先---从左侧开始,一直往上找,找到菱形的顶点结束(不包括菱形顶点),继续下一个继承的父类往上找,找到菱形的顶点结束(不包括菱形顶点),最后找到菱形顶点
经典类(只有py2中才有):深度优先---从左侧开始,一直往上找,找到菱形的顶点结束(包括菱形顶点)继续下一个继承的父类往上找,找到菱形的顶点结束(不包含菱形定点)
不出现菱形问题:正常查找