【发布时间】:2018-11-19 23:10:23
【问题描述】:
我有以下正在被子类化的类:
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
基本上,我希望能够以相反的顺序调用事物,这可能吗?
【问题讨论】:
-
也许您应该实现
__new__()- 它允许您根据传递的参数创建并返回适当子类的实例。__init__()来不及做任何这样的事情,对象已经被创建了。 -
@jasonharper 能否请您说明一下如何在上面完成?
-
@jasonharper 我会在
__new__方法中返回什么?会是return MySQLConnectionManager()吗?
标签: python python-3.x subclassing