Python:如何在调用父类时进行子类化?

时间:2018-11-19 23:10:23

标签: python python-3.x subclassing

我有以下正在被子类化的类:

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

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

1 个答案:

答案 0 :(得分:5)

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

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")

使用factory方法创建子类实例:

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

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

psql.connect()  # "Connecting to Postgres"
mysql.connect()  # "Connecting to MySQL" 
相关问题