pyQt4与继承

2 投票
1 回答
2156 浏览
提问于 2025-04-17 05:01

由于一些原因,我在考虑把我在工作中使用的一个程序重新做成pyqt4的版本(现在是用pygtk做的)。在玩了一段时间,感受了一下这个框架的特点和它在图形界面构建方面的理念后,我遇到了一些烦人的... bug或者实现上的限制。

其中一个问题是关于继承的:

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

有没有人知道这是怎么回事?

1 个回答

2

这不是QT的问题,而是对多重继承工作原理的理解不足。你完全可以使用多重继承,但在Python中这是个比较复杂的主题。

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

想了解更多关于super()在多重继承中如何工作的内容,可以参考以下链接:

撰写回答