在 python 上使用 for 循环创建多个变量

creating more than one variable with for loop on python

我想用我从列表中得到的内容创建多个变量。

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()

我想使用下面列表中的 for 循环重复上面所做的数据库连接。

system_name=['aaa','bbb','ccc','ddd','eee']

您似乎可以从创建 class 中获益。考虑阅读一些 basics of object oriented programming in python.

在你的情况下,可以使用这样的东西:

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]

然后,如果您需要访问列表中的任何系统 my_systems,您可以通过它的索引引用它,例如,如果您想要访问第一个系统的游标,您可以这样做 my_systems[0].cur.

或者,您可以为每个系统创建单独的变量,例如:

aaa = MyClass('aaa', db_type)
bbb = MyClass('bbb', db_type)
ccc = MyClass('ccc', db_type)

在这种情况下,要访问其中一个对象的属性,您可以执行 aaa.cur,例如。