super() returns an instance of a super class that tracks the current position in the MRO. When calling a method on a super instance, super looks up the next class in the MRO and calls the method on that class.
Mark Tolonen give a explanation
class mon():
def __init__(self):
print("i am in mon's init")
print(super())
print(super().__init__)
super().__init__()
class far():
def __init__(self):
print("i am in far's init")
print(super())
print(super().__init__)
super().__init__()
class son(mon,far):
def __init__(self):
print("i am in son's init")
print(super())
print(super().__init__)
super().__init__()
Show the MRO on son
class.
son.__mro__
(<class '__main__.son'>, <class '__main__.mon'>, <class '__main__.far'>, <class 'object'>)
Initialize a son
class to check what super() is
and super().__init__
point to.
x = son()
i am in son's init
<super: <class 'son'>, <son object>>
<bound method mon.__init__ of <__main__.son object at 0x7ff0376f5c70>>
i am in mon's init
<super: <class 'mon'>, <son object>>
<bound method far.__init__ of <__main__.son object at 0x7ff0376f5c70>>
i am in far's init
<super: <class 'far'>, <son object>>
<method-wrapper '__init__' of son object at 0x7ff0376f5c70>
We draw conclusions:
1.super() returns an instance of a super class that tracks the current position in the MRO.
2.When calling a method on a super instance, super looks up the next class in the MRO and calls the method on that class, except the far
class in this example.
The super().__init__
in far
class should point to <class 'object'>
,what does <method-wrapper '__init__' of son object
mean here?
<method-wrapper '__init__' of son object at 0x7ff0376f5c70>
Maybe the output should be:
<bound method object.__init__ of <__main__.son object at 0x7ff0376f5c70>>
If super().__init__
means son.__init__
,all info should output twice.