D
D
Drovosek012019-02-17 16:06:05
Python
Drovosek01, 2019-02-17 16:06:05

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_())

The line is not clear
super().__init__()
Why do we call the initialization of the QWidget class in the Example class? What does this give us? But with simple inheritance (when declaring the Example class, we indicated the QWidget class in parentheses), have we already inherited all the properties and methods or not?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Z
Zanak, 2019-02-25
@Zanak

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 question

Ask a Question

731 491 924 answers to any question