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
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.
© 2024 OneMinuteCode. All rights reserved.