• python2与python3对于多继承的不同策略


    以一个经典的祖孙族谱来解释这个问题:

    class Human:
        def __init__(self):
            print("I'm human")
    
    
    class Mother(Human):
        def __init__(self):
            print("I'm uncle")
    
    
    class Father(Human):
        def __init__(self):
            print("I'm father")
    
    
    class Son(Father,Mother):
        def __init__(self):
            print("I'm son")

    baby = son()

    以上代码的继承逻辑为:


    在经典类范围类,python2采用的是深度优先的继承方式,python采用的是广度优先的方式,下面我来解释一下为什么:

    (1)当把Son的初始化代码注释后,即

    class Son(Father,Mother):
    #     def __init__(sef):
    #         print("I'm son")

    此时,在python2和python3中的中运行的运行结果都为

    >> I'm father

    (2)当继续把Father的初始化代码注释后,即:

    class Father(Human):
        # def __init__(self):
        #     print("I'm father")

    python2中的中运行的运行结果为:

    >> I'm human

    python3中的中运行的运行结果为:

    >> I'm mother

    (3)当继续把Motherr的初始化代码注释后,即:

    class Mother(Human):
        # def __init__(self):
        #     print("I'm uncle")

    此时,在python2和python3中的中运行的运行结果都为

    >> I'm human

    因此python2的多继承策略可如下图红线路径示(深度优先):


    因此python3的多继承策略可如下图红线路径示(广度优先):

  • 相关阅读:
    MZOJ #72 数字
    MZOJ #71 maple做数学题
    MZOJ #70 FFF团
    luogu 2051 [AHOI2009]中国象棋
    uva 280
    uva 260
    文件的基本处理
    文件的基础
    Turtle库
    π的计算
  • 原文地址:https://www.cnblogs.com/erikchanBolg/p/10194322.html
Copyright © 2020-2023  润新知