我正在实现一个python类,它在构造函数中构造另一个对象,该类的类型根据传递给它的参数确定。例如在下面的代码"workerA"
中有类"MyAClass"
和"workerB"
的行为具有"MyBClass"
的行为。基于传递给构造函数的参数实现Python类
我正在使用这种方法,而不是从基类派生不同的类,因为BaseClass已被用于不能更改的不同代码中。所以如果我需要另一个BaseClass的行为,那么我只需要将参数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()
而不是使用'dbtype'参数的下面的代码修改,你可以只是使用正确的课程。 –
@Kluas D,我尝试了传递类的方法,它工作。对我来说,这似乎是我实施的更好的方法。谢谢 – Gourish