我正在研究能够读取文件的低级数据,即映射等的小工具,并使用python的内置sqlite API将结果存储到sqlite DB。
对于已解析的文件数据,我有3个类:
class GenericFile: # general file class
# bunch of methods here
...
class SomeFileObject_A: # low level class for storing objects of kind SomeFileObject_A
# bunch of methods here
...
class SomeFileObject_B: # low level cass for storing objects of kind SomeFileObject_A
# bunch of methods here
...
sqlite接口是作为一个单独的类实现的:
class Database:
def insert(self, object_to_insert):
...
def _insert_generic_file_object(self, object_to_insert):
...
def _insert_file_object_a(self, object_to_insert):
...
def _insert_file_object_b(self, object_to_insert):
...
# bunch of sqlite related methods
当我需要向DB插入一些对象时,我正在使用db.insert(object)
。
现在我认为在我的isinstance
方法中使用insert
可能是个好主意,因为它会处理任何插入的对象,而不需要为每个对象显式调用合适的方法,更优雅。
但是在isinstance
上阅读更多内容之后,我开始怀疑,我的设计并不是那么好。
以下是通用insert
方法的实现:
class Database:
def insert(self, object_to_insert):
self._logger.info("inserting %s object", object_to_insert.__class__.__name__)
if isinstance(object_to_insert, GenericFile):
self._insert_generic_file_object(object_to_insert)
elif isinstance(object_to_insert, SomeFileObject_A):
self._insert_file_object_a(object_to_insert)
elif isinstance(object_to_insert, SomeFileObject_B):
self._insert_file_object_b(object_to_insert)
else:
self._logger.error("Insert Failed. Bad object type %s" % type(object_to_insert))
raise Exception
self._db_connection.commit()
那么,在我的情况下应该避免isinstace
,如果它应该,那么这里有什么更好的解决方案?
由于
答案 0 :(得分:1)
OO的基本原则之一是用多态分派替换显式开关。在您的情况下,解决方案是使用双重调度,因此FileObect
负责知道调用哪个Database
方法,即:
class GenericFile: # general file class
# bunch of methods here
...
def insert(self, db):
return db.insert_generic_file_object(self)
class SomeFileObject_A: # low level class for storing objects of kind SomeFileObject_A
# bunch of methods here
...
def insert(self, db):
return db.insert_file_object_a(self)
class SomeFileObject_B: # low level cass for storing objects of kind SomeFileObject_A
# bunch of methods here
...
def insert(self, db):
return db.insert_file_object_b(self)
class Database:
def insert(self, obj):
return obj.insert(self)