美文网首页Python学习
python2与python3的经典类与新式类的继承

python2与python3的经典类与新式类的继承

作者: cnzhihua | 来源:发表于2018-01-05 16:19 被阅读0次

    python2与python3都有经典类和新式类这两种写法,在python2中经典类和新式类的继承方式不一样,在python3中都一样。
    python2的经典类采用 深度优先搜索 继承方式,新式类采用 广度优先搜索 的继承方式
    python3中经典类和新式类都采用 广度优先搜索 的继承方式

    经典类写法

    class class_name: # 经典类写法
        pass
    

    新式类写法

    class class_name(object): # 新式类写法
        pass
    

    python2 经典类的深度优先搜索继承方式

    举个例子来说明:现有4个类,A,B,C,D类,D类继承于B类和C类,B类与C类继承于A类。


    extends.png

    现在构造函数的继承情况为:

    1. 若D类有构造函数,则重写所有父类的继承
    2. 若D类没有构造函数,B类有构造函数,则D类会继承B类的构造函数
    3. 若D类没有构造函数,B类也没有构造函数,则D类会继承 A类 的构造函数,而 不是C类 的构造函数(经典类继承顺序,详见下面代码)
    4. 若D类没有构造函数,B类也没有构造函数,A类也没有构造函数,则D类才会继承C类的构造函数
    #!/usr/bin/env python
    # _*_ encoding: utf-8 _*_
    
    class A: # 经典类写法
        # pass
        def __init__(self):
            print('running class A construct method')
    
    class B(A):
        pass
        # def __init__(self):
        #     print('running class B construct method')
    
    class C(A):
        def __init__(self):
            print('running class C construct method')
    
    class D(B,C):
        pass
        # def __init__(self):
        #     print('running class D construct method')
    
    D() # result: running class A construct method
    

    分析

    D类没有构造函数,所以从父类中继承,父类的继承顺序为从左往右,所以D类优先从B类中继承,B类没有构造函数,从A类中继承,而不是C类。若A类也没有,才会从C类中继承。这就是深度优先搜索继承的顺序。(D -> B -> A -> C)

    深度优先搜索

    python2 新式类的广度优先搜索继承方式

    还是上面的例子,将经典类改为新式类


    extends.png

    现在构造函数的继承情况为:

    1. 若D类有构造函数,则重写所有父类的继承
    2. 若D类没有构造函数,B类有构造函数,则D类会继承B类的构造函数
    3. 若D类没有构造函数,B类也没有构造函数,则D类会继承 C类 的构造函数,而 不是A类 的构造函数(新式类继承顺序,详见下面代码)
    4. 若D类没有构造函数,B类也没有构造函数,C类也没有构造函数,则D类才会继承A类的构造函数
    #!/usr/bin/env python
    # _*_ encoding: utf-8 _*_
    
    class A(object): # 新式类
        # pass
        def __init__(self):
            print('running class A construct method')
    
    class B(A):
        pass
        # def __init__(self):
        #     print('running class B construct method')
    
    class C(A):
        def __init__(self):
            print('running class C construct method')
    
    class D(B,C):
        pass
        # def __init__(self):
        #     print('running class D construct method')
    
    D() # result: running class C construct method 
    

    分析

    D类没有构造函数,所以从父类中继承,父类的继承顺序为从左往右,所以D类优先从B类中继承,B类没有构造函数,从C类中继承,而不是A类。若C类也没有,才会从A类中继承。这就是广度优先搜索继承的顺序。(D -> B -> C -> A)

    广度优先搜索

    python3的继承方式

    1. python3中经典类与新式类的继承方式 与 python2的新式类继承方式一致,都为广度优先的继承方式(D -> B -> C -> A)
    2. python3中新式类的继承方式是推荐的继承方式

    相关文章

      网友评论

        本文标题:python2与python3的经典类与新式类的继承

        本文链接:https://www.haomeiwen.com/subject/sxmjnxtx.html