微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

尝试创建同时继承 PySide6 类的 Python 抽象类时的元类冲突

如何解决尝试创建同时继承 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_()

我尝试使用以下解决方解决此问题(灵感来自 Resolving metaclass conflictshttp://www.phyast.pitt.edu/~micheles/python/metatype.htmlMultiple inheritance metaclass conflict 等)。

class MyMeta(ABCMeta,type(QWidget)): pass


class MyBaseWidget(QWidget,Metaclass=MyMeta):

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。