根据传递给构造函数的参数实现 Python class

Implement Python class based on the parameter passed to constructor

我正在实现一个 python class,它在构造函数中构造另一个对象,该对象的类型是根据传递给它的参数确定的。例如,在下面的代码中,"workerA" 具有 class "MyAClass" 的行为,而 "workerB" 对象具有 "MyBClass".

的行为

我正在使用此方法,而不是从基础 class 派生不同的 class,因为 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()

我知道这不会产生与您的原始程序相同的输出,但是这样的东西对您有用吗?除非您正在查询方法名称(如上所示),否则您应该会得到功能相同的结果。

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)

或者,使用像这样的 class 扭动:

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)

我根据建议做了以下代码修改

  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)