如何使用动态子类

时间:2015-12-01 17:12:26

标签: python inheritance factory factory-pattern

我还在学习python,我正在尝试学习对象类和继承。

我正在尝试创建一个能够针对具有不同引擎(MySQL,Oracle和MSSQL)的多个不同数据库的脚本。

我有一个名为dbremote的班级和几个较小的班级:MySQLMSSQLORACLE。 class dbremote有一个内部变量:dbtype

每个较小的类具有相同的功能:test connectionperform queryget table structure

我想要做的是使用dbtype调用dbremote,然后调用函数,并让dbremote类使用正确的子类来执行操作。

我希望有人能告诉我如何执行此操作。 感谢。

1 个答案:

答案 0 :(得分:0)

您可以创建一个简单的工厂函数,根据dbtype创建相应类型的实例,然后调用所需的方法。

from xxx import MySQL, MSSQL, ...

def dbremote_factory(dbtype, *args, **kwargs):
    dbremote_cls = { cls.dbtype : cls for cls in [ MySQL, MSSQL, ... ] }[dbtype]
    return dbremote_cls(*args, **kwargs)

dbremote = dbremote_factory('mysql')
print dbremote.test_connection()