6 python subclassing python-3.x
我有以下类正在被子类化:
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
Run Code Online (Sandbox Code Playgroud)
然后,我有一个特定的经理为各种数据库.我可以这样称呼:
c = MySQLConnectionManager()
c._setup_connection(...)
Run Code Online (Sandbox Code Playgroud)
但是,有没有办法做以下事情呢?
c = ConnectionManager("MySQL")
c._setup_connection(x,y,z) # this would call the MySQLConnectionManager,
# not the ConnectionManager
Run Code Online (Sandbox Code Playgroud)
基本上,我希望能够以相反的顺序调用事物,这可能吗?
一种方法是使用静态工厂方法模式.为简洁起见,省略不相关的代码:
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")
Run Code Online (Sandbox Code Playgroud)
使用factory方法创建子类实例:
psql = ConnectionManager.factory("psql")
mysql = ConnectionManager.factory("mysql")
Run Code Online (Sandbox Code Playgroud)
然后根据需要使用您的子类对象:
psql.connect() # "Connecting to Postgres"
mysql.connect() # "Connecting to MySQL"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
156 次 |
| 最近记录: |