簡體   English   中英

在 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 中受益。 考慮閱讀python 中面向 object 編程的一些基礎知識

在你的情況下,可以使用這樣的東西:

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列表中的任何系統,您可以通過其索引引用它,例如,如果您想訪問第一個系統的 cursor,您可以執行my_systems[0].cur

或者,您可以為每個系統創建單獨的變量,例如:

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

在這種情況下,要訪問其中一個對象的屬性,您可以執行aaa.cur ,例如。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM