Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
457 views
in Technique[技术] by (71.8m points)

python - 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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'>

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...