1

I am trying to learn PyQt on my own from rapid gui programming with python and qt and having trouble understanding the meaning/requirement of below line of code mentioned in one of the example in the book.

class Form(QDialog):

        def __init__(self,parent=None):
                super(Form,self).__init__(parent) # Trouble understanding here

So, my question is what is the need of super(Form,self).__init__(parent) or what purpose it is trying to full fill in this code.

RanRag
  • 48,359
  • 38
  • 114
  • 167
  • Actually `__init__()` in this situation appears rather pointless... Is this the ONLY code present in the method? – Joel Cornett May 19 '12 at 21:06
  • No, I have attached the complete code http://pastie.org/3937058 – RanRag May 19 '12 at 21:09
  • Ah, I see. The purpose of `super(...)...` here is to call QDialog's constructor. – Joel Cornett May 19 '12 at 21:14
  • @JoelCornett: But why are we calling the constructor of QDialog what purpose it will full fill. – RanRag May 19 '12 at 21:25
  • 1
    `QDialog` is a base class for dialogs. `QDialog.__init__()` contains all the code necessary to produce a new QDialog object. Since `Form` "overwrites" the original `QDialog.__init__()` with it's own `__init__()`, it needs to explicitly call `QDialog.__init__()` to ensure that that code is executed. – Joel Cornett May 19 '12 at 21:30
  • See this question: http://stackoverflow.com/questions/5166473/inheritance-and-init-method-in-python – Joel Cornett May 19 '12 at 21:35

1 Answers1

2

Take a look at the documentation of super():

Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class. The search order is same as that used by getattr() except that the type itself is skipped.

So basically this line of code:

super(Form,self).__init__(parent)

finds the "closest" set __init__() method in classes from which current class (Form) is inheriting and initiates self object using this method and passing parent as the first argument.

Tadeck
  • 132,510
  • 28
  • 152
  • 198
  • I think he is trying to ask why are we passing `parent` in the constructor as an argument and what role it will play in relation to `PyQt`. – RanRag May 19 '12 at 20:55
  • Yes, @RanRag is right I know what `super` does but why are we passing `parent` as an argument. – RanRag May 19 '12 at 20:58
  • @Noob: You're passing parent as an argument in case you need to set the Form to be a child of another window. Notice that the default is None. – Joel Cornett May 19 '12 at 21:17