python3 super 不适用于 PyQt 类

2024-02-12

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和继承 https://stackoverflow.com/questions/7901178/pyqt4-and-inheritance但没有好的答案。

提前致谢!


和@nneonneo 一起我也怀疑QtCore.QObject不使用合作社super.__init__。如果是的话,你就不会有这个问题了。

但是,您应该意识到,在某些时候,基类之一cannot使用合作超级是因为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您可能想要覆盖的方法,这表明Qtclass 必须是类头中的最后一个。通过没有__init__使用合作超级,即使可以,Qt当其他方法被覆盖时,可以避免进一步出现错误。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python3 super 不适用于 PyQt 类 的相关文章

随机推荐