(I am unable to find a reference anywhere on this matter after some Googling.)
The scenario can be clearly demonstrated with this short code sample:
class X:
def __init__(self, stuff):
self.__stuff = stuff
class Y(X):
def __init__(self, stuff):
# Is it safe to execute statements before calling super.__init__()?
new_stuff = self.call_another_method(stuff)
super(Y, self).__init__(new_stuff)
Using CPython 3.x, the above code sample works -- assuming call_another_method()
exists. It this coding style generally safe, but frowned upon or considered unPythonic? I am unable to find advice on this matter.
Why do I care?
My background comes from more traditional object oriented programming languages such as C++, C#, and Java where "super" must be called strictly as the first statement in a subclass constructor -- ignoring the zero-argument, implicit case.
If it matters, I am a young Pythoneer: 3+, please.
Understanding Python super() with __init__() methods When this method is called it allows the class to initialize the attributes of the class. In an inherited subclass, a parent class can be referred with the use of the super() function.
__init__() of the superclass ( Square ) will be called automatically. super() returns a delegate object to a parent class, so you call the method you want directly on it: super(). area() . Not only does this save us from having to rewrite the area calculations, but it also allows us to change the internal .
The super() function is used to give access to methods and properties of a parent or sibling class. The super() function returns an object that represents the parent class.
The main reason for always calling base class _init__ is that base class may typically create member variable and initialize them to defaults. So if you don't call base class init, none of that code would be executed and you would end up with base class that has no member variables.
Yes, it is perfectly safe to call other things before super()
. Python doesn't set an order, and there are plenty of use-cases for this.
Note that super().__init__()
call is just another expression in Python, it is not a syntax construct. You can use super()
outside methods too, for example, provided you pass in the right arguments.
In your case, you can omit the type and instance arguments, Python 3 will retrieve these for you when super()
is called without arguments, because you are using it in a function defined inside a class:
class Y(X):
def __init__(self, stuff):
new_stuff = self.call_another_method(stuff)
# super(Y, self) is implicit here:
super().__init__(new_stuff)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With