簡體   English   中英

Python:如何在調用父類時進行子類化?

[英]Python: How to subclass while calling parent 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")

使用factory方法創建子類實例:

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

然后根據需要使用您的子類對象:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM