2011-10-26 60 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

如果您發現該回答有用,請將其標記爲已接受。 –