When should I use "parent=None" in __ini__ and "parent" in super()

Cameron Simpson cs at cskk.id.au
Fri Sep 2 19:08:57 EDT 2022


On 23Sep2021 20:38, Mohsen Owzar <mohsen.owzar at gmail.com> wrote:
>I'm writing since almost one-year codes in Python, using TKinter and 
>PyQt5.
>I'm somehow able to writes GUIs in both of them.
>But since I'm using more Pyqt5 and using classes with initialization and super() constructs, and also I saw lots of videos and examples of coding them, I still don’t know exactly how and when should I use the parent in __init()__ and super() construct.

Basicly, q Qt widget can always have a parent. You need to accomodate 
that parameter. Let's look at your first example, which is more correct:

     class MyClass1(QWidget):
         def __init__(self, name, parent=None):
             super(MyClass1, self).__init__(parent)
             print(self.parent().test)

Here's you're defining the initialiser for your MyClass1 subclass. You 
do not specific handle parent, that is handled by the superclass. So:
- accept an optional parent parameter as parameter=None
- pass that parameter to the superclass initialiser for it to handle
- proceed with the rest of your initialiser

Note: when you've got just only superclass, it is simpler to call it's 
initialiser like this:

     super().__init__(parent)

which avoids having to hardwire knowledge of the superclass in this line 
of code.

Your second example is less correct:

     class MyClass2(QWidget):
         def __init__(self, name):
             super(MyClass2, self).__init__()
             print(self.parent().test)

This subclass _does not_ accept an optional parent parameter. The parent 
class accepts an optional parent parameter, as before, but you haven't 
got one to supply and because it is optional in QWidget, things still 
work.

Usually if you're subclassing a single other class, you might try to 
have even less knowledge of the subperclass. Example:

     class MyClass1(QWidget):
         def __init__(self, name, **kw):
             super().__init__(**kw)
             ... do something with name ...

Here you have a parameter you yourself expect to specially handle (name) 
and also accept arbitrary other keyword parameters, which you pass 
straight off to the superclass initialiser. You neither know nor care if 
a parent was supplied, but by passing all the remaining keywork 
parameters you support it anyway.

If you have some special parameters of your own the pattern looks like 
this:

     class MyClass1(QWidget):
         def __init__(self, name, myparam1=None, **kw):
             super().__init__(**kw)
             ... do something with name ...
             ... do something with myparam1 ...

Here your subclass handles name and myparam1, and still leaves the rest 
for the superclass.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Python-list mailing list