如何使declarative_base派生的类符合接口?

时间:2018-08-03 15:29:26

标签: python interface sqlalchemy multiple-inheritance

我有一张桌子:

list

我有一个基类:

constructor(private _el: ElementRef) { }
        @HostBinding('class.show') isOpen = false;
        @HostListener('click') toogleOpen() {
            this.isOpen = !this.isOpen;
            this._el.nativeElement.querySelector('.dropdown-menu').classList.toggle('show')
        }

我有一个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的列名是非常特定于实现的。

1 个答案:

答案 0 :(得分:2)

您可以通过将列名作为第一个参数传递给Column构造函数来将列名与其属性名分开命名,因此WindowsFile既可以实现接口又可以反映表:

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