简体   繁体   中英

Different ways of using __init__ for PyQt4

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, ie 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 parent argument to its base class. If you know that you'll never need the parent arg, that's fine, but this is less flexible.

Since this example only has single inheritance, super(Example, self).__init__(parent) is exactly the same as QtGui.QDialog.__init__(self, parent) ; the former uses super to get a "version" of self that calles QtGui.QDialog 's methods instead of Example 's, so that self is automatically included, while the latter directly calls the function QtGui.QDialog.__init__ and explicitly passes the self and parent arguments. 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, super resolves methods semi-intelligently.

The third example actually uses QWidget instead of QDialog , which is a little weird; presumably that works because QDialog is a subclass of QWidget and doesn't do anything meaningful in its __init__ , but I don't know for sure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM