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