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_()
我尝试使用下面看到的解决方案来解决这个问题(灵感来自解决元类冲突,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
。无法强制执行基类的接口确实剥夺了拥有抽象基类的好处。有什么解决办法吗?
解决方案
推荐阅读
- javascript - CucumberJS 控制台输出 Given,When,Then 运行时的测试步骤
- c++ - CMAKE:“找不到 CMAKE_CXX_COMPILER。”
- firebase - 如何查询具有字段值包含在列表中的文档的 Firestore 集合
- terraform - 如何将用户名和密码通过管道传输到另一个将要执行的命令(BASH)?
- npm - 为什么我的项目需要多个 npmrc 注册表,而工件已经包含它们作为上游源?
- ios - iOS 相当于 Java/Swing 的 FlowLayout 是什么?
- r - 如何从 R 中的数据框中生成包含数据的 QR 码?
- node.js - React Native - 运行“npm start”和“react-native run-android”时出错
- objective-c - 如何将类型化的可变数组从 Swift 返回到 Objective-C?
- ruby-on-rails - -nil:NilClass 的未定义方法“用户”