gpt4 book ai didi

python - 根据传递给构造函数的参数实现Python类

转载 作者:行者123 更新时间:2023-12-01 03:04:56 24 4
gpt4 key购买 nike

我正在实现一个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()

最佳答案

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

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 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)

关于python - 根据传递给构造函数的参数实现Python类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43510763/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com