我有一张 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/