0

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']

  • 1
    Does this answer your question? [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – Unatiel Jun 22 '20 at 10:36

1 Answers1

1

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.

jpnadas
  • 774
  • 6
  • 17
  • Thanks, but i thinked this solution but I do not know how to call these connections separately. for example how do I create a link for my "aaa" database – Yagizdevop Jun 22 '20 at 11:25
  • You really should read the documentation I shared, in any case, I made some edits to the answer to show how you could access attributes of the objects created. – jpnadas Jun 22 '20 at 11:31