我有一个以下模型和抽象基类
import abc
from django.db import models
class AbstractBase():
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def my_method(self):
return
class MyModel(models.Model, AbstractBase):
@abc.abstractmethod
def my_method(self):
return 1
但我收到以下错误。
元类冲突:派生类的元类必须是
(非严格)其所有基类的元类的子类
我认为这里的问题是(正如这里所描述的http://code.activestate.com/recipes/204197-solving-the-metaclass-conflict/)两个不同的元类,因此 python 无法决定将哪个元类用于子对象。
为了解决这个问题,我删除了多重继承并使用以下注册方法来注册子类,
abc.register(Child)
但我不太喜欢这种方法,因为它看起来像猴子修补。
还有其他方法可以解决这个问题吗?
我尝试将模型元类显式分配给 Child 但它不起作用。
我并不是在寻找通过编写代码来解决它的方法。我认为这个问题必须通过改变我的班级结构来解决。
I have a following model and abstract base class
import abc
from django.db import models
class AbstractBase():
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def my_method(self):
return
class MyModel(models.Model, AbstractBase):
@abc.abstractmethod
def my_method(self):
return 1
But I am getting the following error.
metaclass conflict: the metaclass of a derived class must be a
(non-strict) subclass of the metaclasses of all its bases
I think the problem here is (As it is described here http://code.activestate.com/recipes/204197-solving-the-metaclass-conflict/) that two base class has two different metaclasses so python cannot decide which metaclass to use for child object.
In order to solve this I removed multiple inheritence and use following register method to register child class
abc.register(Child)
But I did not really like this approach since it looks like monkey patching.
Is there another way to solve this problem?
I try to assign Model metaclass to Child explicitly but it did not work.
I am not looking for a way to solve it by writing code. I think this must be solved by changing my class structure.
发布评论
评论(1)
除了创建一个继承自
ABCMeta
和ModelBase
的新元类之外,或使您无能为力。ABCMeta
继承自ModelBase
>,但是,不同的注册模式可能是合适的吗?
也许像或者类装饰器?或者在contrib.admin.autodiscover
?.py
文件底部的一个循环,它在适当的类上调用register
(例如,for var in globals().values(): if isinstance(var, type) 和 issubclass(var, AbastractBase): register(var)
)?编辑:哦。我假设
ABCMeta
是一个例子,而不是 <代码>ABCMeta。这就是我在睡眠不足的情况下浏览 StackOverflow 所得到的结果。Apart from creating a new metaclass that inherits from both
ABCMeta
andModelBase
,or makingthere isn't much you can do.ABCMeta
inherit fromModelBase
,However, possibly a different registration pattern might be appropriate?
Maybe something likeOr a class decorator? Or a loop at the bottom of thecontrib.admin.autodiscover
?.py
file which callsregister
on the appropriate classes (ex,for var in globals().values(): if isinstance(var, type) and issubclass(var, AbastractBase): register(var)
)?Edit: D'oh. I'd assumed that
ABCMeta
was an example, notABCMeta
. That's what I get for browsing StackOverflow on too little sleep.