【问题标题】:Multiple Inheritance with Peewee Model and QtCore QObject causing metaclass conflictPeewee Model 和 QtCore QObject 的多重继承导致元类冲突
【发布时间】:2019-02-05 19:58:35
【问题描述】:

首先我是 python 新手,这是我的第一篇文章,如果我在这里做错了什么,请告诉我,我很乐意修复它。

我正在使用 Python 2.7.15rc1 和 Peewee 3.6.4

我想要实现的是创建一个继承自 peewee 模型以及 PySide.QtCore 的 QObject 的类。就像这样:

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

但是这个配置给我带来了以下错误:

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

如果我尝试将 Model 指定为所需的元类(我认为这没问题,因为基本上我只需要与 QObject 的“is a”关系为真),方法是将其添加到 BaseModel:

__metaclass__ = Model

抛出以下错误:

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

另外,通过关注此link,我已将代码更改为:

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

但元类冲突仍然存在。

我在这里做错了什么?

【问题讨论】:

    标签: python python-2.x multiple-inheritance peewee


    【解决方案1】:

    好的。最后我能够通过这样做来解决它:

    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
    

    它工作正常,即使 Eclipse 一直显示此错误:

    Undefined variable from import: __class__
    

    在这一行:

    class Metaclass_Model(Model.__class__):
    

    【讨论】:

      猜你喜欢
      • 2012-06-30
      • 2011-09-27
      • 2015-04-27
      • 1970-01-01
      • 2021-10-30
      • 2021-05-01
      • 2011-11-20
      • 2012-11-14
      相关资源
      最近更新 更多