zoukankan      html  css  js  c++  java
  • python2中新式类和经典类的多重继承调用顺序

    class A:
    def foo(self):
    print('called A.foo()')

    class B(A):
        pass
    
    class C(A):
        def foo(self):
            print('called C.foo()')
    
    class D(B, C): 
        pass
    
    if __name__ == '__main__':
        d = D() 
        d.foo()
    

    B、C 是 A 的子类,D 多继承了 B、C 两个类,其中 C 重写了 A 中的 foo() 方法。

    如果 A 是经典类(如上代码),当调用 D 的实例的 foo() 方法时,Python 会按照深度优先的方法去搜索 foo() ,路径是 B-A-C ,执行的是 A 中的 foo() ;

    如果 A 是新式类,当调用 D 的实例的 foo() 方法时,Python 会按照广度优先的方法去搜索 foo() ,路径是 B-C-A ,执行的是 C 中的 foo() 。

    因为 D 是直接继承 C 的,从逻辑上说,执行 C 中的 foo() 更加合理,因此新式类对多继承的处理更为合乎逻辑。

  • 相关阅读:
    标准函数头部注释
    排序
    #define _INTSIZEOF(n)
    并发编程资料
    memory model
    Ubuntu搜狗输入法的使用
    gprof
    xml_editor
    创建本地Ubuntu镜像
    设计模式9:建造者模式
  • 原文地址:https://www.cnblogs.com/leisurelylicht/p/python2zhong-xin-shi-lei-he-jing-dian-lei-de-duo-z.html
Copyright © 2011-2022 走看看