Multiple inheritance metaclass conflict(多重继承元类冲突)
问题描述
我需要一个类的双重继承.我尝试了几种语法,但我不明白元类的概念.
I need a double inheritance for a class. I tried several syntaxes but I don't understand the concept of metaclass.
from PyQt5.QtGui import QStandardItem
from configparser import ConfigParser
class FinalClass(ConfigParser, QStandardItem):
def __init__(self, param):
ConfigParser.__init__(self)
QStandardItem.__init__(self)
推荐答案
你的问题是你尝试继承的类有不同的元类:
The problem in your case is that the classes you try to inherit from have different metaclasses:
>>> type(QStandardItem)
<class 'sip.wrappertype'>
>>> type(ConfigParser)
<class 'abc.ABCMeta'>
因此,python 无法决定哪个应该是新创建的类的元类.在这种情况下,它必须是继承自 sip.wrappertype
(或旧 PyQt5 版本的 PyQt5.QtCore.pyqtWrapperType
)和 ABCMeta
的类代码>.
Therefore python can't decide which should be the metaclass for the newly created class. In this case, it would have to be a class inheriting from both sip.wrappertype
(or PyQt5.QtCore.pyqtWrapperType
for older PyQt5 versions) and ABCMeta
.
因此,元类冲突可以通过显式引入这样的元类来解决:
Therefore the metaclass conflict could be resolved by explicitly introducing such a class as metaclass like this:
from PyQt5.QtGui import QStandardItem
from configparser import ConfigParser
class FinalMeta(type(QStandardItem), type(ConfigParser)):
pass
class FinalClass(ConfigParser, QStandardItem, metaclass=FinalMeta):
def __init__(self, param):
ConfigParser.__init__(self)
QStandardItem.__init__(self)
如果您想要更详细的描述,这篇文章是一个好的开始.
If you want a more detailed description, this article is a good start.
但是我不太相信在这种情况下使用多重继承是一个好主意,特别是与 QObjects 一起使用多重继承可能会很棘手.也许将 ConfigParser 对象存储为实例变量并在需要时使用它会更好.
However I'm not really convinced that using multiple inheritance for this situaction is such a good idea, specially using multiple inheritance together with QObjects can be tricky. Maybe it would be better to just store the ConfigParser object as an instance variable and use that when needed.
这篇关于多重继承元类冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:多重继承元类冲突
基础教程推荐
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 筛选NumPy数组 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01