Multi inheritance and super() usage in Python

Keywords: Programming Python

Tested for an afternoon, Internet search for a long time, really this difference makes me depressed! The most depressing thing is that the documents on python's official website don't have such a detailed introduction

 

Python classes are divided into two types, one is called classic class and the other is called new class. Both support multiple inheritance.

  • Case 1:

B inherits A, C inherits A and B

# Classical class
class A():
    def __init__(self):
    print 'A'

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

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

When C needs to call the init() function of the parent class, the former will cause the init() function of the parent class A to be called twice, which is inefficient and does not conform to the DRY principle. Therefore, the following new method is available

# New class
class A(object):
    def __init__(self):
        print 'A'

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

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

When super() mode is adopted, the first parent class in the first multi inheritance will be found automatically, so there is no need to call twice

  • Case two:

B inherits A, D inherits C and B

class A(object):
    def __init__(self):
        print 'A'

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

class C(object):
    def __init__(self):
        print 'C'

class D(B, C):
    def __init__(self):
        super(B, self).__init__()
        C.__init__(self)
        print 'B'

The initialization of the two classes is different. Only B needs to trace the parent class and use super (), and the other needs to follow the old method to initialize

  • Case three:

Diamond inheritance, B inherits A, C inherits A, D inherits B and C

class A():
    def __init__(self):
        print('enter A')
        print('leave A')


class B(A):
    def __init__(self):
        print('enter B')
        super().__init__()
        print('leave B')


class C(A):
    def __init__(self):
        print('enter C')
        super().__init__()
        print('leave C')


class D(B, C):
    def __init__(self):
        print('enter D')
        super().__init__()
        print('leave D')


d = D()

Using super() can avoid the problem of constructor being called twice

##The experiment tested case 1 and case 2. If there is any modification or mistake, please correct it

Reference:

https://www.jackyshen.com/2015/08/19/multi-inheritance-with-super-in-Python/

https://www.runoob.com/python/python-func-super.html

Posted by EsOne on Tue, 04 Feb 2020 06:56:11 -0800