【发布时间】:2018-04-25 08:01:44
【问题描述】:
我最近遇到了TypeError,当我将QMainWindow 与PyQt5 子类化时我不明白。
创建两个类时:
class Base (QMainWindow):
def __init__(self):
super(Base, self).__init__(None)
class Base2 (object):
def __init__(self, a, b):
pass
然后创建两者的子类,不带任何初始化参数:
class SubClass( Base, Base2 ):
def __init__(self):
Base.__init__(self)
Base2.__init__(self, 0,0)
创建子类的实例时出现 TypeError:
from PyQt5.QtWidgets import QApplication, QMainWindow
app = QApplication([])
print( SubClass() )
输出:
Traceback (most recent call last):
print(SubClass())
Base.__init__(self)
super(Base, self).__init__(None)
TypeError: __init__() missing 2 required positional arguments: 'a' and 'b'
但是,当更改继承 class SubClass( Base2, Base ): 的顺序时,代码将运行良好。
我阅读了How does Python's super() work with multiple inheritance? 和Method Resolution Order 的帖子,但没有找到答案。
(另请注意,这有点特定于 PyQt,因为我无法完全基于 object 重现基类的问题)
有人可以对这种行为给出明确的解释吗?
【问题讨论】:
-
您的实现有很多错误,因此无法做出明确的解释。将
super与显式__init__调用混用总是错误的——所有基类都必须使用super。您还需要修复对不匹配签名的处理 - 请参阅 this answer 和 this answer 您链接到的第一个问题。一旦消除了这些问题,基类的顺序就不再重要了。
标签: python pyqt pyqt5 multiple-inheritance method-resolution-order