pyQt4 和继承 [英] pyQt4 and inheritance
问题描述
出于多种原因,我正在考虑重做我在 pyqt4 中使用的程序(目前它在 pygtk 中).在玩弄它并感受它并通过 gui 构建欣赏它的哲学之后,我遇到了一些烦人的......错误或实现限制
For a number of reasons I am contemplating redoing an program I use at work in pyqt4 (at present it is in pygtk). After playing around with it and getting a feel for it and appreciating its philosophy with gui building I am running into some annoying ... bugs or implementation limitations
其中之一是继承:
#!/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
虽然我期待:
$ 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来初始化继承的类?我宁愿没有待办事项
Why is it that you cannot use super to initialise the inherited classes when a qt4 class is involved? I would rather not have todo
QtGui.QMainWindow.__init__()
A.__init__()
有人知道这是怎么回事吗?
Anyone know what is going on?
推荐答案
这不是 QT 问题,而是缺乏对多重继承如何工作的理解.你绝对可以使用多重继承,但这在 Python 中是一个棘手的话题.
This is not a QT issue, but a lack of understanding of how multiple inheritance works. You can absolutely use multiple inheritance, but it is a tricky subject in Python.
简而言之,在您的最后一个示例中,第一个 __init__
被调用,因此如果您将 class D(QtGui.QMainWindow,A):
更改为 class D(A, QtGui.QMainWindow):
你会看到 A
的构造函数被调用,而不是 QMainWindow
的构造函数.
In a nutshell, in your last example, the first __init__
is called, so if you changed class D(QtGui.QMainWindow,A):
to class D(A, QtGui.QMainWindow):
you would see A
's constructor called, and not QMainWindow
's one.
有关具有多重继承的 super()
行为的进一步参考,请参阅以下链接:
See the following links for further reference on super()
behavior with multiple inheritance:
- Python 的 super() 如何处理多重继承?一个>
- http://python-history.blogspot.com/2010/06/method-resolution-order.html
这篇关于pyQt4 和继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!