So… I’m working on trying to move from basic Python to some GUI programming, using PyQt4. I’m looking at a couple different books and tutorials, and they each seem to have a slightly different way of kicking off the class definition.
One tutorial starts off the classes like so:
class Example(QtGui.QDialog):
def __init__(self):
super(Example, self).__init__()
Another book does it like this:
class Example(QtGui.QDialog):
def __init__(self, parent=None):
super(Example, self).__init__(parent)
And yet another does it this way:
class Example(QtGui.QDialog):
def__init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
I’m still trying to wrap my mind around classes and OOP and super() and all… am I correct in thinking that the last line of the third example accomplishes more or less the same thing as the calls using super() in the previous ones, by explicitly calling the base class directly? For relatively simple examples such as these, i.e. single inheritance, is there any real benefit or reason to use one way vs. the other? Finally… the second example passes parent as an argument to super() while the first does not… any guesses/explanations as to why/when/where that would be appropriate?
The first one simply doesn’t support passing a
parentargument to its base class. If you know that you’ll never need theparentarg, that’s fine, but this is less flexible.Since this example only has single inheritance,
super(Example, self).__init__(parent)is exactly the same asQtGui.QDialog.__init__(self, parent); the former usessuperto get a “version” ofselfthat callesQtGui.QDialog‘s methods instead ofExample‘s, so thatselfis automatically included, while the latter directly calls the functionQtGui.QDialog.__init__and explicitly passes theselfandparentarguments. In single inheritance there’s no difference AFAIK other than the amount of typing and the fact that you have to change the class name if you change inheritance. In multiple inheritance,superresolves methods semi-intelligently.The third example actually uses
QWidgetinstead ofQDialog, which is a little weird; presumably that works becauseQDialogis a subclass ofQWidgetand doesn’t do anything meaningful in its__init__, but I don’t know for sure.