首页 > 解决方案 > 尝试创建同时继承 PySide6 类的 Python 抽象类时的元类冲突

问题描述

我正在尝试创建一个也继承任意 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_()

我尝试使用下面看到的解决方案来解决这个问题(灵感来自解决元类冲突http: //www.phyast.pitt.edu/~micheles/python/metatype.html ,多重继承元类冲突等)。

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。无法强制执行基类的接口确实剥夺了拥有抽象基类的好处。有什么解决办法吗?

标签: pythonpyqtpysidepyside2pyside6

解决方案


推荐阅读