I want to create multiple variables with what I get from the list.
cm_aaa = TRYModule()
app_label='aaa'
schema_aaa=cm_aaa.get_schema(app_label, db_type)
cm_aaa.connect(app_label, db_type)
cur_aaa=cm_aaa.conn.cursor()
cm_bbb=TRYModule()
app_label='bbb'
schema_bbb=cm_bbb.get_schema(app_label, db_type)
cm_bbb.connect(app_label, db_type)
cur_bbb=cm_bbb.conn.cursor()
I want to make the database connection repetitions I made above with the for loop from the list below.
system_name=['aaa','bbb','ccc','ddd','eee']
It seems like you could benefit from creating a class. Consider having a read of some basics of object oriented programming in python.
In your case, something like this could be used:
class MyClass:
def __init__(self, app_label, db_type):
self.cm = TRYModule()
self.app_label = app_label
self.db_type = db_type
self.schema = self.cm.get_schema(self.app_label, self.db_type)
self.cm.connect(self.app_label, self.db_type)
self.cur = self.cm.conn.cursor()
system_name = ['aaa','bbb','ccc','ddd','eee']
my_systems = [MyClass(label, db_type) for label in system_name]
Then, if you need to access any of the systems on the list my_systems
you reference it via its index, for instance, if you want to access cursor of the first system you can do my_systems[0].cur
.
Alternatively, you could create separate variables for each of the systems, such as:
aaa = MyClass('aaa', db_type)
bbb = MyClass('bbb', db_type)
ccc = MyClass('ccc', db_type)
In this case, to access an attribute of one of the objects, you can do aaa.cur
, for instance.