python super()

super() 函数是用于调用父类(超类)的一个方法。

super() 是用来解决多重继承问题的,直接用类名调用父类方法(A.init()或者A.add())在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等种种问题。

MRO 就是类的方法解析顺序表, 其实也就是继承父类方法时的顺序表。

# 单继承
class A:
    def __init__(self):
        print("A init")
        self.a = "a_init"
    def add(self, x):
         y = x+1
         print(y)
         print(self.a)
class B(A):
    def __init__(self):
        # 父类初始化
        # 如过注释掉这行,导致父类A没有进行初始化,调用父类的self.a就会报错找不到变量a
        # 因为classB有构造函数,所以实列化B()是不会执行父类的魔法方法__init__()
        super(B,self).__init__()
        print("B init")
    def add(self, x):
        # 使用super()调用父类的同名方法
        super(B,self).add(x)
        print("B method")



if __name__ == "__main__":

    b = B()
    b.add(2)  # 3
A init
B init
3
a_init
B method
# 多继承
class A:
    def __init__(self):
        print("A init")
class B(A):
    def __init__(self):
        # super(B,self).__init__()
        A.__init__(self)
        print("B init")
class C(A):
    def __init__(self):
        # super(C,self).__init__()
        A.__init__(self)
        print("C init")
class D(B,C):
    def __init__(self):
        # super(D,self).__init__()
        B.__init__(self)
        C.__init__(self)
        print("D init")


if __name__ == "__main__":

    b = D()
# 使用类.对象方式调用父类构造函数
A init
B init
A init
C init
D init
# 使用super()调用父类构造函数
A init
C init
B init
D init
# 结论,类.对象方式,会造成重复执行的问题,super()不会

PS:

子类不定义构造函数时候,默认引用父类构造函数

子类定义了构造函数,默认不会引用父类构造函数

子类定义了构造函数,如果需要使用父类构造函数需要显示调用
多继承,钻石继承:https://blog.csdn.net/feilzhang/article/details/80443194
MRO:https://blog.csdn.net/come_from_pluto/article/details/90483447

posted @ 2022-04-02 10:42  左岸丶  阅读(39)  评论(0编辑  收藏  举报