Answer the question
In order to leave comments, you need to log in
Why in a child class call the initialization of the parent class in Python?
I'm reading about PyQt5, I saw the following code on the site:
import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QIcon
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 300, 220)
self.setWindowTitle('Icon')
self.setWindowIcon(QIcon('web.png'))
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
super().__init__()
Answer the question
In order to leave comments, you need to log in
First, shouldn't the super call look like this: super(Example, self).__init__()
?
When we override a method in a child class, we can re-implement all the work of this method, and then the call to super is not needed at all.
If we only want to change the method's behavior a little, then we're left with inlining the parent's method call at the appropriate place, telling the runtime what type of parent we're looking for (in your case, Example) and a reference to the current instance (it's self).
Now to actually answer your question: initializing a parent class can be a tricky process, because the properties of an ancestor can themselves be objects that are important to construct and initialize correctly, and if you're not prepared to do it yourself every time you create a new child, then you can call super.
Just call it right. :)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question