我正在尝试创建一个抽象基类,它也继承了一个任意的 PySide6 类。但是,以下会产生错误 TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
。
from abc import ABC, abstractmethod
from PySide6.QtWidgets import QApplication, QWidget
class MyBaseWidget(QWidget, ABC):
def __init__(self, parent=None):
super().__init__(parent=parent)
@abstractmethod
def foo(self):
pass
class MyConcreteWidget(MyBaseWidget):
def __init__(self, parent=None):
super().__init__(parent=parent)
app = QApplication([])
widget = MyConcreteWidget()
widget.show()
app.exec_()
我尝试使用以下解决方案解决此问题(灵感来自 Resolving metaclass conflicts、http://www.phyast.pitt.edu/~micheles/python/metatype.html、Multiple inheritance metaclass conflict 等)。
class MyMeta(ABCMeta, type(QWidget)): pass
class MyBaseWidget(QWidget, metaclass=MyMeta):
def __init__(self, parent=None):
super().__init__(parent=parent)
@abstractmethod
def foo(self):
pass
class MyConcreteWidget(MyBaseWidget):
def __init__(self, parent=None):
super().__init__(parent=parent)
app = QApplication([])
widget = MyConcreteWidget()
widget.show()
app.exec_()
这在执行时没有错误,但在实例化 TypeError: Can't instantiate abstract class MyConcreteWidget with abstract methods foo
时我预计会出现类似 MyConcreteWidget
的错误。无法强制执行基类的接口确实会失去拥有抽象基类的好处。有什么解决办法吗?