+ 3
About super()
Why in the code below output is "2"? Why super() doesn't print "1" before it? class A: def __init__(self): print(1) class B(A): def __init__(self): super(A, self).__init__() print(2) obj=B() >>> 2 >>>
3 Respuestas
+ 4
The call of B on super() calls the Class A, but the instance self. This means it would use the methods of B, but the Class is A. The methods are inherited from the instance reference, so A is not inherited.
+ 8
I had to ask Google because I'd never seen the syntax super(A, self).__init__() before, only super().__init__(). Turns out that super(A, self).__init__() is python 2 syntax. In python 3, you just use super().__init__() [https://stackoverflow.com/questions/576169/understanding-python-super-with-init-methods].
If you do so, it will print both 1 (from the base class constructor) and 2 (from the child class constructor).
I'm not sure why you get different results for super(A, self).__init__() and super().__init__() in python 3, but in general you probably shouldn't use python 2 syntax in python 3.
+ 7
#I guess it calls superclass of A (object) and object.__init__ does nothing
#https://stackoverflow.com/questions/8611712/what-does-objects-init-method-do-in-JUMP_LINK__&&__python__&&__JUMP_LINK
class S:
def __init__(self):
print('S')
class A(S):
def __init__(self):
print('A')
class B(A):
def __init__(self):
super(B, self).__init__() #A
print()
super(A, self).__init__() #S
B()