python - 如何使 declarative_base 派生类符合接口(interface)?

标签 python interface sqlalchemy multiple-inheritance

我有一张 table :

CREATE TABLE `windows_files` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `filepath` varchar(260) DEFAULT NULL,
  `timestamp` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
);

我有一个基类:

class File:
    path: str
    modified: datetime.datetime

    def delete(self):
        os.remove(self.path)

我有一个 declarative_base 派生类:

Base = declarative_base()

class WindowsFile(File, Base):
    __tablename__ = 'windows_files'
    id = Column(Integer, primary_key=True)
    filepath = Column(String(260))
    timestamp = Column(DateTime)

问题是,WindowsFile 不是一个很好的File:

>>> file = session.query(WindowsFile).first()
>>> ...
>>> file.delete()
Traceback (most recent call last):
  File "<pyshell#34916>", line 1, in <module>
...
    os.remove(self.path)
AttributeError: 'WindowsFile' object has no attribute 'path'

如何使 WindowsFile 适合界面,隐藏其实现细节?我无法更改数据库,因为其他东西正在使用它,并且我无法更改 File 的定义,因为 windows_files 的列名称非常特定于实现。

最佳答案

您可以通过将列名作为第一个参数传递给 Column 构造函数来单独命名列及其属性名称,这样 WindowsFile 既可以实现该接口(interface),又可以反射(reflect)表:

class WindowsFile(File, Base):
    __tablename__ = 'windows_files'
    id = Column(Integer, primary_key=True)
    path = Column('filepath', String(260))
    modified = Column('timestamp', DateTime)

关于python - 如何使 declarative_base 派生类符合接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51675879/

相关文章:

java - Android,我如何在 Controller 中使用 hellper 方法的回调?

python - Pyramid : "Unknown column ' 中的 OperationalError 1054、 'field list' XX'

python - 当没有这样的命名列时,SQLite 给出找不到列的错误

python - fatal error : numpy/arrayobject. h:没有那个文件或目录

python - 使用 imshow 校正轴

python - 如何在 google colab 上使用 Box 2 D

python - 如何关闭 SQLAlchemy implicit_returning?

python - 如何使用位于不同 NAT 上的套接字在 2 个 Python 程序之间进行通信?

java - 如何从 Clojure 中的类调用具体化的 Java 接口(interface)?调用电话无法解决

c# - 我怎样才能使这段代码更通用