我有以下正在被子类化的类:
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/