【发布时间】:2017-12-08 07:51:48
【问题描述】:
这个问题更多的是关于如何使用 OOP 读取数据库。 SQLite 和 sqlite3 只是可以使用的示例,并不是问题的主旨:
我正在创建一个软件包,它允许用户查询已经生成的 SQLite 索引文件。对于非常特殊的情况,查询以某种方式索引的 SQLite 文件基本上是一种语法,这应该很简单,但我有点困惑如何“自动”读取 SQLite
这是一个示例(带有伪代码):
import sqlite3
Class EasySQL:
def __init__(self, filepath):
self.filepath = filepath
def connect(self, filepath): ## perhaps this should be above in init?
return sqlite3.connect(self.filepath)
def query_indexA(self):
## query index A on SQLite3 connection
我希望在实例化类时“自动”连接到 SQLite 数据库:
### instantiate class
my_table1 = EasySQL("path/to/file")
目前,用户需要在实例化后调用函数.connect()。
my_table = EasySQL("path/to/file")
the_object_to_do_queries = my_table.connect()
## now users can actually use this
the_object_to_do_queries.query_indexA()
这似乎是一种糟糕的形式,而且不必要地复杂。
如何编写初始化方法立即创建SQLite3连接?
希望这个问题很清楚。如果没有,我很乐意编辑。
【问题讨论】:
标签: python python-3.x class oop initialization