7

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 和继承,但没有好的答案。

提前致谢!

4

1 回答 1

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也可以避免在覆盖其他方法时进一步降低错误。

于 2012-10-12T19:48:37.753 回答