【发布时间】:2012-03-25 06:43:38
【问题描述】:
所以我有一堆使用 SQLAlchemy 的表,这些表被建模为从结果继承到对 declarative_base() 的调用的对象。即:
Base = declarative_base()
class Table1(Base):
# __tablename__ & such here
class Table2(Base):
# __tablename__ & such here
等等。然后我想为我的每个 DB 表类提供一些通用功能,the easiest way to do this according to the docs 就是做多重继承:
Base = declarative_base()
class CommonRoutines(object):
@classmethod
def somecommonaction(cls):
# body here
class Table1(CommonRoutines, Base):
# __tablename__ & such here
class Table2(CommonRoutines, Base):
# __tablename__ & such here
我不喜欢的一点是 A) 一般而言,多重继承有点棘手(解决诸如 super() 调用等问题会很棘手),B) 如果我添加一个新表,我必须记住从Base 和CommonRoutines 继承,并且C)在某种意义上确实是“CommonRoutines”类“is-a”类型的表。真正的CommonBase 是一个抽象基类,它定义了一组所有表共有的字段和例程。换句话说:“its-a”抽象表。
所以,我想要的是这样的:
Base = declarative_base()
class AbstractTable(Base):
__metaclass__ = ABCMeta # make into abstract base class
# define common attributes for all tables here, like maybe:
id = Column(Integer, primary_key=True)
@classmethod
def somecommonaction(cls):
# body here
class Table1(AbstractTable):
# __tablename__ & Table1 specific fields here
class Table2(AbstractTable):
# __tablename__ & Table2 specific fields here
但这当然行不通,因为我必须 A) 为 AbstractTable 定义一个 __tablename__,B) 事物的 ABC 方面会导致各种头痛,C) 必须指出某种AbstractTable 和每个单独的表之间的数据库关系。
所以我的问题是:是否有可能以合理的方式实现这一目标?理想情况下,我想强制执行:
- 没有多重继承
-
CommonBase/AbstractTable是抽象的(即不能实例化)
【问题讨论】:
标签: python sqlalchemy multiple-inheritance