链条传动

砥砺前行,不忘初心!

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''
多继承:按照继承顺序,从左往右,谁在前面先继承谁
'''

'''
class C1:
    def f1(self):
        pass

    def f2(self):
        pass

class C2:
    def f2(self):
        pass

class C3(C2,C1):
    def f3(self):
        pass


# obj = C3()
# obj.f1()
# obj.f2()
# obj.f3()

obj = C3()
obj.f2()  #执行的是C2的f2方法,因为C3是先继承的C2,然后继承的C1(就是看继承顺序,谁在前面先继承谁)
'''

'''
class C0:
    def f2(self):
        print('C0')

class C1(C0):
    def f1(self):
        pass

class C2:
    def f2(self):
        print('C2')

class C3(C1,C2):
    def f3(self):
        pass

obj = C3()
obj.f2()  #先查找C3中是否有f2,没有再查找C1种是否有f2,没有继续查找C1的父类C0是否有f2,还是没有的话才会到C2中去查找是否有f2
'''

class C_2:
    def f2(self):
        print('C_2')

class C_1(C_2):
    def f_1(self):
        print('C_1')

class C0(C_2):
    def f0(self):
        print('C0')

class C1(C0):
    def f1(self):
        pass

class C2(C_2):
    def f2(self):
        print('C2')

class C3(C1,C2):
    def f3(self):
        pass

obj = C3()
obj.f2()  #当C3继承的C1和C2继承了同一个父类(或者是父类之上继承了同一个类),查找方法时,是找到最顶层类的下一级类,然后又查找平行的类,最后才找最顶层的类

 

 

多继承查找方法顺序:

 

"""
使用类的__mro__方法来查看类的继承顺序
__mro__ """ class F4(object): pass class F3(F4): pass class F2_5(object): pass class F2(F2_5): pass class F1(F2, F3): pass print(F1.__mro__) # 查看F1类的继承顺序 结果: [<class '__main__.F1'>, <class '__main__.F2'>, <class '__main__.F2_5'>, <class '__main__.F3'>, <class '__main__.F4'>, <class 'object'>]

 

posted on 2016-11-07 13:46  链条君  阅读(132)  评论(0编辑  收藏  举报