我需要一个类的双重继承.我尝试了几种语法,但我不明白元类的概念.
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.
这篇关于多重继承元类冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!