Python: 如何在调用parent class 的同时subclass?

Python: How to subclass while calling parent class?

我有以下 class 正在被子class编辑:

class ConnectionManager(object):

    def __init__(self, type=None):

        self.type = None

        self.host = None
        self.username = None
        self.password = None
        self.database = None
        self.port = None


    def _setup_connection(self, type):
        pass

然后我有一个针对各种数据库的特定管理器。我可以这样称呼它们:

c = MySQLConnectionManager()
c._setup_connection(...)

但是,有没有办法改为执行以下操作?

c = ConnectionManager("MySQL")
c._setup_connection(x,y,z) # this would call the MySQLConnectionManager, 
                           # not the ConnectionManager

基本上,我希望能够以相反的顺序调用事物,这可能吗?

一种方法是使用静态工厂方法模式。为简洁起见,省略不相关的代码:

class ConnectionManager:
    # Create based on class name:

    @staticmethod
    def factory(type):
        if type == "mysql": return MySqlConnectionManager()
        if type == "psql": return PostgresConnectionManager()
        else:
            # you could raise an exception here
            print("Invalid subtype!")

class MySqlConnectionManager(ConnectionManager):
    def connect(self): print("Connecting to MySQL")

class PostgresConnectionManager(ConnectionManager):
    def connect(self): print("Connecting to Postgres")

使用工厂方法创建子类实例:

psql = ConnectionManager.factory("psql")
mysql = ConnectionManager.factory("mysql")

然后根据需要使用您的子类对象:

psql.connect()  # "Connecting to Postgres"
mysql.connect()  # "Connecting to MySQL"