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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.