手记

python 多继承使用基础

class Root(object):
    def __init__(self):
        print("this is  Root")

class B(Root):
    print("enter B")
    def __init__(self):
        print("enter B")
        super(B,self).__init__()
        print("leave B")

class C(Root):
    print("enter C")
    def __init__(self):
        print("enter C")
        super(C,self).__init__()
        print("leave C")

class D(B,C):
    pass

if __name__ == '__main__':
    d = D();
    print(d.__class__.__mro__)

python 支持多继承,此处 D 继承自B 和 C,然后 B 和 C 又继承自己 Root

mro 记录了变量的查找顺序,使用就近原则
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.Root'>, <class 'object'>)
打印结果 ,查找顺序使用广度优先模式
enter B
enter C
enter B
enter C
this is  Root
leave C
leave B

Root 在 B和 C处都有引用 ,但多重继承的目的其实就是变量的查找,如果有公共的父类只会去引用查找一次

0人推荐
随时随地看视频
慕课网APP