(Python3) What is the difference between super() and super(A, self)?

Asked 2 years ago, Updated 2 years ago, 138 views

class A:
    def __init__(self):
        print("A")

class B(A):
    def __init__(self):
        super().__init__()

b = B()

class A:
    def __init__(self):
       print("A")

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

b = B()

The output values are the same when you use these two methods. So what's the difference?

And

class A:
    def __init__(self):
        print("A")

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

b = B()

What is the information that this code doesn't work?

class python inheritance

2022-09-21 19:22

1 Answers

Even if you inherit only one class, you still have the advantage of super()code. If you need to change the class name if you want to code in super(B, self) format, you also need to change the super(B, self) syntax. This will not happen if you write super() code. In addition, if you implement diamond-shaped multiple inheritance, i.e. B that inherited A and D that inherited A and C that inherited A, you have a problem if you do not use the super() code. First, you cannot call a constructor of two parent classes in the form of super(B, self). And even if you call it B._init___(self) C._init___(self), the generator of A is called twice, causing a bug that the program does not move as expected or the code is repeated, causing a delay. If you use super(), that won't happen. If you use super() for all parts, coding is easy and functional. For the last code, if you enter A.__init__(self), it is executed, but not recommended.


2022-09-21 19:22

If you have any answers or tips

Popular Tags
python x 4647
android x 1593
java x 1494
javascript x 1427
c x 927
c++ x 878
ruby-on-rails x 696
php x 692
python3 x 685
html x 656

© 2024 OneMinuteCode. All rights reserved.