从http://docs.sqlalchemy.org/en/improve_toc/orm/extensions/declarative/mixins.html#augmenting-the-base我看到你可以在基类中定义方法和属性。
我想确保所有子类都实现了特定的方法。但是,在尝试定义这样的抽象方法时:
import abc
from sqlalchemy.ext.declarative import declarative_base
class Base(metaclass=abc.ABCMeta):
@abc.abstractmethod
def implement_me(self):
pass
Base = declarative_base(cls=Base)
class Child(Base):
__tablename__ = 'child'
我收到错误TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
我试图找到一些文档或示例来帮助我,但是很简单。
答案 0 :(得分:5)
看起来您可以将元类传递给declarative_base
。默认的元类是DeclarativeMeta
- 所以,我认为关键是要创建一个新的元类,它是abc.ABCMeta
和DeclarativeMeta
的混合:
import abc
from sqlalchemy.ext.declarative import declarative_base, DeclarativeMeta
class DeclarativeABCMeta(DeclarativeMeta, abc.ABCMeta):
pass
class Base(declarative_base(metaclass=DeclarativeABCMeta)):
__abstract__ = True
@abc.abstractmethod
def implement_me(self):
"""Canhaz override?"""
*未测试