python3中有一个简单的程序:
from PyQt4 import QtCore
import PyQt4
class Bar(object):
def __init__(self):
print("Bar start")
super(Bar, self).__init__()
print("Bar end")
class FakeQObject(object):
def __init__(self):
print("FakeQObject start")
super(FakeQObject, self).__init__()
print("FakeQObject end")
class Foo(QtCore.QObject, Bar):
#class Foo(FakeQObject, Bar):
def __init__(self):
print("Foo start")
super(Foo, self).__init__()
print("Foo end")
print(Foo.__mro__)
print(PyQt4.QtCore.PYQT_VERSION_STR)
f = Foo()
a)当类Foo继承自QtCore.QObject和Bar时,我们得到:
(<class '__main__.Foo'>, <class 'PyQt4.QtCore.QObject'>, <class 'sip.wrapper'>, <class 'sip.simplewrapper'>, <class '__main__.Bar'>, <class 'object'>)
4.9.4
Foo start
Foo end
b)当类Foo继承自FakeQObject和Bar时,我们得到:
(<class '__main__.Foo'>, <class '__main__.FakeQObject'>, <class '__main__.Bar'>, <class 'object'>)
4.9.4
Foo start
FakeQObject start
Bar start
Bar end
FakeQObject end
Foo end
问题是:为什么在a)的情况下,Bar init没有被调用?
我在pyQt4 and inheritance找到了类似的问题,但没有好的答案。
提前致谢!
答案 0 :(得分:3)
与@nneonneo一起,我也怀疑QtCore.QObject
没有使用合作社super.__init__
。如果是这样,你就不会有这个问题。
但是,您应该知道,在某些时候,其中一个基类不能使用合作超级,因为object
将不具备该方法。考虑:
class Base():
def __init__(self):
print("initializing Base")
super().__init__()
def helper(self, text):
print("Base helper")
text = super().helper(text)
text = text.title()
print(text)
class EndOfTheLine():
def __init__(self):
print("initializing EOTL")
super().__init__()
def helper(self, text):
print("EOTL helper")
text = super().helper(text)
return reversed(text)
class FurtherDown(Base, EndOfTheLine):
def __init__(self):
print("initializing FD")
super().__init__()
def helper(self, text):
print(super().helper(text))
test = FurtherDown()
print(test.helper('test 1 2 3... test 1 2 3'))
和输出:
initializing FD
initializing Base
initializing EOTL
Base helper
EOTL helper
Traceback (most recent call last):
File "test.py", line 28, in <module>
print(test.helper('test 1 2 3... test 1 2 3'))
File "test.py", line 25, in helper
print(super().helper(text))
File "test.py", line 7, in helper
text = super().helper(text)
File "test.py", line 17, in helper
text = super().helper(text)
AttributeError: 'super' object has no attribute 'helper'
因此,无论哪个课程都是行尾,都不需要拨打super
。因为您可能希望覆盖其他Qt
方法,这表明Qt
类必须是类标头中的最后一个。如果没有__init__
使用合作超级,即使它可以,Qt
可以在重写某些其他方法时进一步避免错误。