问题描述
我创建了一个用于管理消息服务订阅的类。由于与每个订阅的配置相关的原因,该类实例化三个单独的客户端,每个类的实例也实例化三个。为了将三个客户端的实例化减少为一个 for 循环,我使用了 __getattribute__
和 __setattr__
。我已经阅读了有关这些方法的其他主题,但我不确定像我这样使用它们是否会导致问题。这是一个非常简单的例子:
class BaseClient(object):
def __init__(self,name):
self.name = name
def connect(self):
return 'client logged on'
def do_other_things(self):
return 'other things done'
class MsgServiceListener(object):
def __init__(self):
self.client1 = None
self.client2 = None
self.client3 = None
self.clientNames = ['client1','client2','client3']
def createAndSubscribe(self):
for client in self.clientNames:
if not self.__getattribute__(client):
self.__setattr__(client,BaseClient(client))
self.__getattribute__(client).connect()
self.__getattribute__(client).do_other_things()
我利用下划线方法的方式有什么问题吗?
解决方法
您应该使用 __setattr__
和 __getattr__
...
__getattribute__
/getattr(self,client)
(或 setattr(self,client,value)
)
但更好的是,如果您需要将名称映射到对象,您应该只使用 dict。
class MsgServiceListener:
def __init__(self):
self.clients = {}
self.clientNames = ["client1","client2","client3"]
def createAndSubscribe(self):
for client in self.clientNames:
self.clients[client] = c = BaseClient(client)
c.connect()
c.do_other_things()