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

标签 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

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

最佳答案

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

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" 

关于Python:如何在调用父类时进行子类化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53383957/

相关文章:

python - Pandas fillna 到空字典

python - 删除重复项但保留对删除行的引用

python - 登录 Python 脚本不起作用 : results in empty log files

wpf - 子类化 WPF 窗口

c# - C# 中是否可以使用类初始值设定项?

python - 使用子进程在 python 2.7 中获取尾命令输出

python-3.x - 支持向量回归

python - 为什么一个多重继承的Exception没有捕捉到父异常?

python - 列出本地网络设备python的IP/MAC/名称

c++ - 为什么编译器找不到父类(super class)的方法?