問題描述
我需要一個類的雙重繼承.我嘗試了幾種語法,但我不明白元類的概念.
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)
推薦答案
你的問題是你嘗試?yán)^承的類有不同的元類:
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 無法決定哪個應(yīng)該是新創(chuàng)建的類的元類.在這種情況下,它必須是繼承自 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)
如果您想要更詳細(xì)的描述,這篇文章是一個好的開始.
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.
這篇關(guān)于多重繼承元類沖突的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!