因此,我有一堆使用SQLAlchemy的表,它们被建模为对象,这些对象从结果继承到对declarative_base()
的调用。即:
Base = declarative_base()
class Table1(Base):
# __tablename__ & such here
class Table2(Base):
# __tablename__ & such here
然后,我想为我的每个数据库表类提供一些通用功能,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
是一个抽象基类,它定义了所有表通用的一组字段和例程。换句话说,“它是一个”抽象表。
所以,我想要的是:
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)为__tablename__
定义AbstractTable
,B)事物的ABC方面引起各种麻烦,C)必须指出某种数据库关系在AbstractTable
和每个单独的表之间。
所以我的问题是:是否有可能以合理的方式实现这一目标?理想情况下,我想强制执行:
没有多重继承CommonBase
/ AbstractTable
是抽象的(即无法实例化)
python大神给出的解决方案
这很简单,只需使declarative_base()
返回使用Base
参数从CommonBase
继承的cls=
类。也显示在Augmenting The Base文档中。然后,您的代码可能类似于以下内容:
class CommonBase(object):
@classmethod
def somecommonaction(cls):
# body here
Base = declarative_base(cls=CommonBase)
class Table1(Base):
# __tablename__ & Table1 specific fields here
class Table2(Base):
# __tablename__ & Table2 specific fields here
Python sqlite3数据库已锁定 - python我在Windows上使用Python 3和sqlite3。我正在开发一个使用数据库存储联系人的小型应用程序。我注意到,如果应用程序被强制关闭(通过错误或通过任务管理器结束),则会收到sqlite3错误(sqlite3.OperationalError:数据库已锁定)。我想这是因为在应用程序关闭之前,我没有正确关闭数据库连接。我已经试过了: connectio…
Python pytz时区函数返回的时区为9分钟 - python由于某些原因,我无法从以下代码中找出原因:>>> from pytz import timezone >>> timezone('America/Chicago') 我得到:<DstTzInfo 'America/Chicago' LMT-1 day, 18:09:00 STD…
用大写字母拆分字符串,但忽略AAA Python Regex - python我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…
如何打印浮点数的全精度[Python] - python我编写了以下函数,其中传递了x,y的值:def check(x, y): print(type(x)) print(type(y)) print(x) print(y) if x == y: print "Yes" 现在当我打电话check(1.00000000000000001, 1.0000000000000002)它正在打印:<…
Python:检查新文件是否在文件夹中[重复] - pythonThis question already has answers here: How do I watch a file for changes? (23个答案) 3年前关闭。 我是python的新手,但是我尝试创建一个自动化过程,其中我的代码将侦听目录中的新文件条目。例如,某人可以手动将zip文件复制到一个特定的文件夹中,并且我希望我的代码能够在文件完全…