gpt4 book ai didi

python-3.x - python3 super 不适用于 PyQt 类

转载 作者:行者123 更新时间:2023-12-04 12:42:16 32 4
gpt4 key购买 nike

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

提前致谢!

最佳答案

与@nneonneo 一起,我还怀疑 QtCore.QObject不使用合作super.__init__ .如果是这样,你就不会有这个问题了。

但是,您应该知道在某些时候基类之一不能使用协作 super ,因为 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 class 必须是类头中的最后一个。由于没有 __init__使用合作 super ,即使它可以, Qt当某些其他方法被覆盖时,正在进一步避免错误。

关于python-3.x - python3 super 不适用于 PyQt 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12351976/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com