Python继承的作用和菱形问题

继承的作用

可以利用继承来减少代码冗余

class Person:
    school='aaaa'

    def __init__(self,name,age,):
        self.name=name
        self.age=age

class Teacher(Person):
    pass

class Student(Person):
    pass

#类实例化会自动调用__init__如果类中没有,去父类中找
# stu1=Student() #报错,因为父类中必须传两个参数
stu1=Student('nick',18)
print(stu1.school)

多层继承

'''
Python大型免费公开课,适合初学者入门
加QQ群:579817333 获取学习资料及必备软件。
'''
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中才有):深度优先—从左侧开始,一直往上找,找到菱形的顶点结束(包括菱形顶点)继续下一个继承的父类往上找,找到菱形的顶点结束(不包含菱形定点)

不出现菱形问题:正常查找

posted @ 2022-10-07 20:27  I'm_江河湖海  阅读(2)  评论(0编辑  收藏  举报