0

我正在开发一个小工具,它能够读取文件的低级数据,即映射等,并将结果存储到 sqlite DB,使用 python 的内置 sqlite API。

对于解析的文件数据,我有 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在我的情况下应该避免,如果应该,这里有什么更好的解决方案?

谢谢

4

1 回答 1

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)
于 2015-12-29T08:57:51.553 回答