While investigating this question, I came across this strange behavior of single-argument super
:
Calling super(some_class).__init__()
works inside of a method of some_class
(or a subclass thereof), but throws an exception when called anywhere else.
Code sample:
class A():
def __init__(self):
super(A).__init__() # doesn't throw exception
a = A()
super(A).__init__() # throws exception
The exception being thrown is
Traceback (most recent call last):
File "untitled.py", line 8, in <module>
super(A).__init__() # throws exception
RuntimeError: super(): no arguments
I don't understand why the location of the call makes a difference.
It's well-known that the zero-argument form of super
performs magic:
The zero argument form only works inside a class definition, as the compiler fills in the necessary details to correctly retrieve the class being defined, as well as accessing the current instance for ordinary methods.
However, no such statement exists for the one-argument form of super
. On the contrary:
Also note that, aside from the zero argument form, super() is not limited to use inside methods.
So, my question is, what exactly is happening under the hood? Is this the expected behavior?