I have created a class for managing subscriptions to a messaging service. The class instantiates three separate clients for reasons related to the configuration for each subscription, also three per instance of the class. To reduce the instantiation of the three clients to one for loop, I've used __getattribute__ and __setattr__. I've read other threads about these methods, and I'm not sure if using them as I have could lead to issues. Here is a very simplified example:
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()
Is there anything wrong with the way I've harnessed the underscore methods?
Instead of using the dunder methods
__setattr__/__getattr__(or__getattribute__), you should usegetattr(self, client)andsetattr(self, client, value)...but better yet, you should just use a dict if you need to map names to objects.