PyQt4 and inheritance

For a number of reasons, I am considering a re-program that I use at work in pyqt4 (it is currently in pygtk). After playing with him and feeling him and appreciating his philosophy with the creation of gui, I encounter some unpleasant errors or implementation restrictions.

One of them is inheritance:

#!/usr/bin/env python #-*- coding: utf-8 -*- import sys from PyQt4 import QtCore, QtGui app = QtGui.QApplication(sys.argv) class A(object): def __init__(self): print "A init" class B(A): def __init__(self): super(B,self).__init__() print "B init" class C(QtGui.QMainWindow): def __init__(self): super(C,self).__init__() print "C init" class D(QtGui.QMainWindow,A): def __init__(self): print "D init" super(D,self).__init__() print "\nsingle class, no inheritance" A() print "\nsingle class with inheritance" B() print "\nsingle class with Qt inheritance" C() print "\nsingle class with Qt inheritance + one other" D() 

If I run this, I get:

 $ python test.py single class, no inheritance A init single class with inheritance A init B init single class with Qt inheritance C init single class with Qt inheritance + one other D init 

when i was expecting:

 $ python test.py single class, no inheritance A init single class with inheritance A init B init single class with Qt inheritance C init single class with Qt inheritance + one other D init A init 

Why can't you use super to initialize inherited classes when the qt4 class is involved? I would prefer not todo

 QtGui.QMainWindow.__init__() A.__init__() 

Does anyone know what is going on?

+2
source share
1 answer

This is not a QT problem, but a lack of understanding of how multiple inheritance works. You can absolutely use multiple inheritance, but this is a complex question in Python.

In short, in your last example, the first __init__ is called, so if you change class D(QtGui.QMainWindow,A): to class D(A, QtGui.QMainWindow): you will see constructor A , not QMainWindow alone.

See the following links for more help on the behavior of super() with multiple inheritance:

+2
source

All Articles