【问题标题】:creating more than one variable with for loop on python在 python 上使用 for 循环创建多个变量
【发布时间】:2020-06-22 10:33:02
【问题描述】:

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

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

【问题讨论】:

标签: python database postgresql for-loop connection


【解决方案1】:

您似乎可以从创建课程中受益。考虑阅读一些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,例如。

【讨论】:

  • 谢谢,但我想到了这个解决方案,但我不知道如何分别调用这些连接。例如,如何为我的“aaa”数据库创建链接
  • 你真的应该阅读我分享的文档,无论如何,我对答案进行了一些编辑,以展示如何访问创建的对象的属性。
猜你喜欢
  • 1970-01-01
  • 2015-12-26
  • 2019-01-26
  • 1970-01-01
  • 2018-02-18
  • 2012-01-21
  • 2021-04-23
  • 2022-01-22
  • 1970-01-01
相关资源
最近更新 更多