我正在实现一个python类,它在构造函数中构造另一个对象,其类型是根据传递给它的参数确定的。例如,在下面的代码"workerA"
中,类"MyAClass"
和"workerB"
对象的行为具有"MyBClass"
的行为。
我使用此方法而不是从基类派生不同的类,因为BaseClass已经在不能更改的不同代码中使用。因此,如果我想要BaseClass的另一个行为和"MyBClass"
行为,那么我只需要将参数dbtype = "MyBClass"
传递给它。
有没有更好的方法可以使用,并给出相同的结果?
import sys
# MyAClass definition
class MyAClass :
def __init__(self, serverSettings):
self._serverSettings = serverSettings
def initialize(self):
self._init = 1;
print("Calling", sys._getframe(1).f_code.co_name)
def add(self):
self._init = 2;
print("Calling", sys._getframe(1).f_code.co_name)
def finalize(self):
self._init = 3;
print("Calling", sys._getframe(1).f_code.co_name)
def __del__(self):
print('Calling destructor of class ', self.__class__.__name__)
# MyBClass definition
class MyBClass :
def __init__(self, serverSettings):
self._serverSettings = serverSettings
def initialize(self):
self._init = 1;
print("Calling", sys._getframe(1).f_code.co_name)
def add(self):
self._init = 2;
print("Calling", sys._getframe(1).f_code.co_name)
def finalize(self):
self._init = 3;
print("Calling", sys._getframe(1).f_code.co_name)
def __del__(self):
print('Calling destructor of class ', self.__class__.__name__)
# The base class which will be called in main program
class BaseClass :
def __init__(self, serverSettings, dbtype = None):
if(dbtype == None):
self.__worker = MyAClass(serverSettings)
elif(dbtype == "MyBClass") :
self.__worker = MyBClass(serverSettings)
else :
print("Undefined type")
def initialize(self):
self.__worker.initialize()
def add(self):
self.__worker.add()
def finalize(self):
self.__worker.finalize()
if __name__ == "__main__":
serverSettings = dict()
serverSettings["address"] = "localhost"
serverSettings["name"] = "Testname"
workerA = BaseClass(serverSettings)
workerA.add()
workerB = BaseClass(serverSettings, dbtype = "MyBClass")
workerB.finalize()
答案 0 :(得分:2)
我知道这不会产生与原始程序相同的输出,但是这样的东西会用于您的目的吗?除非您查询方法名称(如上所述),否则您应该获得功能相同的结果。
class BaseClass :
def __init__(self, serverSettings, dbtype=None):
if(dbtype == None):
self.__worker = MyAClass(serverSettings)
elif(dbtype == "MyBClass") :
self.__worker = MyBClass(serverSettings)
else :
print("Undefined type")
def __getattribute__(self, x):
settings = object.__getattribute__(self, '__dict__').get('_BaseClass__worker')
return settings.__getattribute__(x)
或者,使用像这样的一些类twizzing:
class BaseClass :
def __init__(self, serverSettings, dbtype='MyAClass'):
dbtypes = {'MyAClass': MyAClass,
'MyBClass': MyBClass}
if dbtype not in dbtypes:
raise("Undefined type")
self.__class__ = dbtypes[dbtype]
self.__init__(serverSettings)
答案 1 :(得分:0)
我根据建议
进行了以下代码更改 class BaseClass :
def __init__(self, serverSettings, Classtype = MyAClass):
authclasses = [MyAClass, MyBClass]
if Classtype not in authclasses :
self.__worker = MyAClass(serverSettings)
else :
self.__worker = MyBClass(serverSettings)
def __getattribute__(self, x):
settings = object.__getattribute__(self, '__dict__').get('_BaseClass__worker')
return settings.__getattribute__(x)