2011-10-26 47 views
2

由于很多原因,我正在考虑重做我在pyqt4中使用的程序(目前它在pygtk中)。 玩了,并得到一个感受它,欣赏它与我遇到一些烦人......错误或实施限制GUI建筑理念后pyQt4和继承

其中之一就是继承:

#!/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() 

如果我运行此我得到:

$ 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 

,而我所期待的:

$ 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 

为什么当涉及qt4类时,您不能使用super来初始化继承类?我宁愿没有待办事项

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

任何人都知道发生了什么事?

回答

2

这不是QT问题,但缺乏对多继承如何工作的理解。你绝对可以使用多重继承,但这是Python中一个棘手的主题。

简而言之,在你最后一个例子,第一个__init__被调用,所以如果你改变class D(QtGui.QMainWindow,A):class D(A, QtGui.QMainWindow):你会看到A的构造函数调用,而不是QMainWindow的一个。

查看super()行为与多重继承作进一步参考以下链接:

+0

MMK所以更没有使用超级随后的情况。 a .__ init __(self)它是。谢谢 – Naib

+0

如果您发现该回答有用,请将其标记为已接受。 –