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的多继承策略可如下图红线路径示(广度优先):

猜你喜欢

转载自blog.csdn.net/jiaming917/article/details/85334793
今日推荐