python类-super

super的定义为:

super ( [ type [, object-or-type ] ] )具体说明可以参见python文档,主要用途有两种情况

1)单继承时用来引用父类各种方便

2)多继承时可以区分具体调用哪个父类的方法


代码示例:

单继承

class A(object): 
    def __init__(self):
        self.x = 1
        self.y = 3


    def testA(self):
        print(self.x)


class B(A):
    def __init__(self):
        #这个不需要参数直接调用super函数
        #因为不需要写父类的名字,维护起来很方便,即使父类名字变更代码变更小
        super().__init__()
        self.x = 2
        
    def testB(self):
        print(self.x)


    def testB2(self):
        print(self.y)
        
if __name__ == '__main__':
    b = B()
    b.testB()
    b.testA()
    b.testB2()

多继承

对于super(B, self).__init__()是这样理解的:super(B, self)首先找到B的父类,然后把类B的对象self转换为类A的对象, 然后“被转换”的类A对象调用自己的__init__函数。

      A.print
    /   \    
   B    C
    \   /  
      D
类似菱形继承的情况, 如果不使用super的情况,则在D中会出现调用两次A.print的情况

例1
class A(object): 
    def __init__(self):
        print('testA')

class B(A):
    def __init__(self):
        A.__init__(self)
        print('testB')

class C(A):
    def __init__(self):
        A.__init__(self)
        print('testC')

class D(B,C):
    def __init__(self):
        B.__init__(self)
        C.__init__(self)
        print('TestD')
        
if __name__ == '__main__':
    d = D()
输出:
testA
testB
testA
testC
TestD

例二
class A(object): 
    def __init__(self):
        print('testA')


class B(A):
    def __init__(self):
        #为什么不用参数,因为super会自动找到父类,
        #并把super参数的self转换成父类的对象,然后再调用__init__
        #也就是说这个是通过instance调用的,已经不需要再制定instance
        #而类定义时候的self,是为instance预留的位置,所以需要
        super(B,self).__init__() 
        print('testB')

class C(A):
    def __init__(self):
        super(C,self).__init__()
        print('testC')


class D(B,C):
    def __init__(self):
        super(D,self).__init__()
        print('TestD')
        
if __name__ == '__main__':
    d = D()
输出:
testA
testC
testB
TestD

可以看到,这里只是调用了一次Super但是他会把继承的B和C的__init__都会执行一次。

<本节完>


你可能感兴趣的:(python)