简体   繁体   English

Peewee模型和QtCore QObject的多重继承导致元类冲突

[英]Multiple Inheritance with Peewee Model and QtCore QObject causing metaclass conflict

First of all I'm new to python and that is my first post so, please, let me know if I did something wrong around here and I'll gladly fix it. 首先,我是python新手,这是我的第一篇文章,所以,请让我知道我在这里是否做错了什么,我会很乐意修复它。

I'm using Python 2.7.15rc1 and Peewee 3.6.4 我正在使用Python 2.7.15rc1和Peewee 3.6.4

What I'm trying to achieve is create a class that inherits from peewee's Model and also from PySide.QtCore's QObject. 我要实现的目标是创建一个从peewee的Model以及PySide.QtCore的QObject继承的类。 Just like this: 像这样:

class BaseModel(Model, QObject):

id = PrimaryKeyField()

class Meta:
    database = db  

def __str__(self):
    return str(self.__dict__)

def __eq__(self, other): 
    return self.id == other.id

But this configuration brings me the following error: 但是这种配置给我带来了以下错误:

TypeError: Error when calling the metaclass bases
metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases

If I try to specify Model as the desired metaclass (and I think it is ok because basically I only need the "is a" relation with QObject to be true) by adding this to BaseModel: 如果我尝试将Model指定为所需的元类(并且我认为可以,因为基本上我只需要QObject的“ is a”关系为true),就可以将其添加到BaseModel中:

__metaclass__ = Model

The following error is thrown: 引发以下错误:

AttributeError: 'Model' object has no attribute '_meta'

also, by following this link , I've changed code to this: 另外,通过点击此链接 ,我将代码更改为此:

class A (Model):
    pass
class B (QObject):
    pass
class C(A, B):
    pass

class BaseModel(A, B):

    __metaclass__ = C

    id = PrimaryKeyField()

    class Meta:
        database = db  

    def __str__(self):
        return str(self.__dict__)

    def __eq__(self, other): 
        return self.id == other.id

But the metaclass conflict persists. 但是元类冲突仍然存在。

What am I doing wrong around here? 我在这附近做错了什么?

Ok. 好。 Finally I was able to solve it by doing this: 最终,我能够通过执行以下操作解决问题:

class Metaclass_Model(Model.__class__):
    pass
class Metaclass_QObject(QObject.__class__):
    pass

class MultiMetaclass(Metaclass_Model, Metaclass_QObject):
    pass


class BaseModel(Model, QObject):

    __metaclass__ = MultiMetaclass

    id = PrimaryKeyField()

    class Meta:
        database = db  

    def __str__(self):
        return str(self.__dict__)

    def __eq__(self, other): 
        return other is not None and self.id == other.id

It works fine, even though Eclipse keeps showing this error: 即使Eclipse不断显示此错误,它也能正常工作:

Undefined variable from import: __class__

at this line: 在这一行:

class Metaclass_Model(Model.__class__):

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM