zoukankan      html  css  js  c++  java
  • 理解Python中的继承规则和继承顺序

    先来看一段代码:

    class First(object):
        def __init__(self):
            print ("first")
    
    
    class Second(object):
        def __init__(self):
            print ("second")
    
    
    class Third(object):
        def __init__(self):
            print ("third")
    
    
    class Forth(object):
        def __init__(self):
            print ("forth")
    
    
    class Five(First, Second, Third, Forth):
        def __init__(self):
            print ("that's it")
    
    a = Five()
    
    

    这段代码的输出结果是:

    that's it
    

    也就是说,在class Five中的def__init__(self)override了父类(classes: First, Second, Third, Forth)的def__init__(self)

    class First(object):
        def __init__(self):
            print ("first")
    
    
    class Second(object):
        def __init__(self):
            print ("second")
    
    
    class Third(object):
        def __init__(self):
            print ("third")
    
    
    class Forth(object):
        def __init__(self):
            print ("forth")
    
    
    class Five(First, Second, Third, Forth):
        def __init__(self):
            super().__init()__
            print ("that's it")
    
    a = Five()
    
    

    输出结果是:

    first
    that's it
    

    也就是说,class Five先继承了父类 Firstdef __init__(self),然后执行自己重新定义的def __init__(self)

    如果在所有父类中也使用super().__init__,事情变得有趣:

    class First(object):
        def __init__(self):
            super().__init__()
            print ("first")
    
    
    class Second(object):
        def __init__(self):
            super().__init__()
            print ("second")
    
    
    class Third(object):
        def __init__(self):
            super().__init__()
            print ("third")
    
    
    class Forth(object):
        def __init__(self):
            super().__init__()
            print ("forth")
    
    
    class Five(First, Second, Third, Forth):
        def __init__(self):
            super().__init__()
            print ("that's it")
    
    a = Five()
    

    这段代码的输出结果是:

    forth
    third
    second
    first
    that's it
    

    也就是说,如果在父类中都加入super()class Five执行父类中def __init__()的顺序是class Forth -> class Third -> class Second -> class First

    也就是说,class Five在继承了class First后,不会马上停止并执行class FIrst中的def __init__(),而是继续往下搜寻,直到最后。

  • 相关阅读:
    C++课程学习笔记第六周:多态
    C++课程学习笔记第五周:继承
    C++课程学习笔记第四周:运算符的重载
    C++课程学习笔记第三周:类和对象提高
    C++课程学习笔记第一周:从C到C++
    C++课程学习笔记第二周:类和对象基础
    PyTorch的安装及学习资料
    PyTorch练手项目一:训练一个简单的线性回归
    PyTorch练手项目二:MNIST手写数字识别
    PyTorch练手项目四:孪生网络(Siamese Network)
  • 原文地址:https://www.cnblogs.com/yaos/p/7071190.html
Copyright © 2011-2022 走看看