![](/img/trans.png)
[英]How to create a collection class which automatically adds new aggregation methods based on inherited class?
[英]How to create a class which restricts methods based on the input file? Creating a database API
这个问题更多的是关于如何使用OOP读取数据库。 SQLite和sqlite3只是可以使用的示例,并不是问题的主要重点。 (可以说,Python仅用于解释我的观点):
我正在创建一个软件包,允许用户查询已经生成的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
def query_indexB(self):
## query index B on SQLite3 connection
def query_indexC(self):
## query index C on SQLite3 connection
def query_indexD(self):
## query index D on SQLite3 connection
这是我的问题:用户只能访问两种类型的索引SQLite文件。 “类型1”文件仅在A和B上建立索引-该SQLite文件中不存在索引C和D,并且如果用户尝试调用这些函数,则应该引发错误。 “类型2”文件仅在C和D上建立索引-该SQLite文件中不存在索引A和B,并且如果用户尝试调用这些函数,则应该引发错误。
我如何“限制”这些方法,以便如果用户在“ Type 1” SQLite文件上调用(例如) query_indexC
,那么会出现错误?
我强烈希望不要强迫用户使用两个单独的类,因为这太复杂了,例如EasySQL_Type1()
或EasySQL_Type2()
尽管类型可以的标志。
如果可以正确识别文件类型,则可以轻松地将其存储为内部引用,并在尝试访问“无效”索引时引发错误。 您还可以在__init__()
建立与SQLite文件的连接,因为没有网络驱动器,因此不需要重新连接处理。
当然,有一些极端情况,但这应该可以帮助您入门:
import sqlite3
class EasySQL(object):
def __init__(self, filepath, index_type=1): # type 1 by default
self.connection = sqlite3.connect(filepath)
self.index_type = index_type
def query_indexA(self):
if self.index_type != 1:
raise ValueError("indexA can only be queried by index type 1")
# do your indexA processing... your DB is available in self.connection
def query_indexB(self):
if self.index_type != 1:
raise ValueError("indexB can only be queried by index type 1")
# do your indexB processing... your DB is available in self.connection
def query_indexC(self):
if self.index_type != 2:
raise ValueError("indexC can only be queried by index type 2")
# do your indexC processing... your DB is available in self.connection
def query_indexD(self):
if self.index_type != 2:
raise ValueError("indexD can only be queried by index type 2")
# do your indexD processing... your DB is available in self.connection
现在,您的用户可以使用以下命令启动它:
type1_db = EasySQL("path/to/their/file.sqlite", 1) # for type 1, or
type2_db = EasySQL("path/to/their/file.sqlite", 2) # for type 2
而且,如果他们尝试使用与其类型无关的方法,则会引发ValueError
。 如果您不想让用户提供他们的数据库文件的类型,则必须设计一种从文件本身(名称,架构等)确定它的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.