zoukankan      html  css  js  c++  java
  • 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的多继承策略可如下图红线路径示(广度优先):

  • 相关阅读:
    [Leetcode] Median of Two Sorted Arrays
    [Jobdu] 题目1463:招聘会
    [Leetcode] Merge Two Sorted Lists
    [Leetcode] Combinations
    [Leetcode] Populating Next Right Pointers in Each Node II
    [Leetcode] Insertion Sort List
    redis在Web中的使用
    设计模式:单例模式
    设计模式:基本法则
    设计模式:工厂模式
  • 原文地址:https://www.cnblogs.com/erikchanBolg/p/10194322.html
Copyright © 2011-2022 走看看