python 继承类 super() 程序执行顺序

一直困惑于python继承类的程序执行顺序,看了这段代码后理解得到了加深,跟大家分享一下学习心得。

单继承

class FooParent(object):
    def __init__(self):
        self.parent = 'I\'m the parent.'
        print ('Parent')
    
    def bar(self,message):
        print ("%s from Parent" % message)
 
class FooChild(FooParent):
    def __init__(self):
        # super(FooChild,self) 首先找到 FooChild 的父类(就是类 FooParent),然后把类 FooChild 的对象转换为类 FooParent 的对象
        super(FooChild,self).__init__()    
        print ('Child')
        
    def bar(self,message):
        super(FooChild, self).bar(message)
        print ('Child bar fuction')
        print (self.parent)
 
if __name__ == '__main__':
    fooChild = FooChild()
    fooChild.bar('HelloWorld')

输出结果如下。

Parent
Child
HelloWorld from Parent
Child bar fuction
I’m the parent.

执行顺序分析:

  1. super()父类的__init__
  2. 子类的__init__
  3. super()继承父类的bar方法
  4. 子类的bar方法

作用:super()避免了基类的显式调用,即super(FooChild,self).init()与FooParent.init()等价
说明__init__中的super()会继承父类中的self.parent,将上述代码修改如下

class FooParent(object):
    def __init__(self):
        # self.parent = 'I\'m the parent.'
        print ('Parent')
    
    def bar(self,message):
        print ("%s from Parent" % message)
 
class FooChild(FooParent):
    def __init__(self):
        # super(FooChild,self) 首先找到 FooChild 的父类(就是类 FooParent),然后把类 FooChild 的对象转换为类 FooParent 的对象
        # super(FooChild,self).__init__()    
        print ('Child')
        
    def bar(self,message):
        super(FooChild, self).bar(message)
        print ('Child bar fuction')
        # print (self.parent)
 
if __name__ == '__main__':
    fooChild = FooChild()
    fooChild.bar('HelloWorld')

Child
HelloWorld from Parent
Child bar fuction

可见,并没有执行父类__init__中的代码
同理注释掉第二个super()结果如下

class FooParent(object):
    def __init__(self):
        # self.parent = 'I\'m the parent.'
        print ('Parent')
    
    def bar(self,message):
        print ("%s from Parent" % message)
 
class FooChild(FooParent):
    def __init__(self):
        # super(FooChild,self) 首先找到 FooChild 的父类(就是类 FooParent),然后把类 FooChild 的对象转换为类 FooParent 的对象
        # super(FooChild,self).__init__()    
        print ('Child')
        
    def bar(self,message):
        # super(FooChild, self).bar(message)
        print ('Child bar fuction')
        # print (self.parent)
 
if __name__ == '__main__':
    fooChild = FooChild()
    fooChild.bar('HelloWorld')

Child
Child bar fuction

多继承

对于多层继承关系,python会通过创建一个MRO(Method Resolution Order)列表,它代表了类继承的顺序。使用super()后,程序查看MRO列表,自动进入上一级的类。

class Base(object):
    def __init__(self):
        print ("enter Base")
        print ("leave Base")

class A(Base):
    def __init__(self):
        print ("enter A")
        super(A, self).__init__()
        print ("leave A")

class B(Base):
    def __init__(self):
        print ("enter B")
        super(B, self).__init__()
        print ("leave B")

class C(A, B):
    def __init__(self):
        print ("enter C")
        super(C, self).__init__()
        print ("leave C")
 
if __name__ == '__main__':
    C()
    print(C.mro())

enter C
enter A
enter B
enter Base
leave Base
leave B
leave A
leave C
[<class ‘main.C’>, <class ‘main.A’>, <class ‘main.B’>, <class ‘main.Base’>, <class ‘object’>]

注意class C(B, A)与class C(A,B)是有差异,调用上级类的现后顺序存在差别

参考

https://www.runoob.com/python/python-func-super.html
https://www.jianshu.com/p/8ddb595628d1

### Python继承 `object` 时使用 `super()` 的方法及作用 在 Python 3.x 版本中,所有默认都是新式,并隐式地继承自 `object`。显式声明继承 `object` 主要是为了保持向后兼容性和提高代码可读性。 当子继承 `object` 并使用 `super()` 函数时,这有助于简化对父初始化和其他方法的调用过程。下面是一个具体的例子来展示如何实现这一点: ```python class MyClass(object): def __init__(self, value): self.value = value print(f"MyClass init called with {value}") class MySubClass(MyClass): def __init__(self, value, extra): super().__init__(value) # 调用了MyClass的__init__ self.extra = extra print(f"MySubClass init also called with {extra}") ``` 在这个案例里,创建 `MySubClass` 实例时不仅会执行自身的初始化逻辑还会自动触发其基 (`MyClass`) 初始化函数[^2]。 #### 使用场景分析 - **确保父被正确初始化**:即使未来更改了继承结构或增加了中间层,只要遵循 MRO (Method Resolution Order),就能保证各个层次上的构造器都能得到恰当处理。 - **避免硬编码依赖关系**:相比于直接指定某个特定型的名称作为参数传递给内置 `type.__bases__`, 或者通过其他手段获取当最近的一个非抽象别;利用 `super()` 可让程序更加灵活且易于维护。 - **支持多重继承下的协作模式**:对于复杂的应用来说,多个祖先可能都需要参与到同一个操作当中去——比如设置共享资源、注册事件处理器等等。此时借助于 C3 线性化算法所决定的最佳顺序依次访问每一个参与者就显得尤为重要了[^1]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值