【问题标题】:Using variables from one .py file in a loop in another .py file在另一个 .py 文件的循环中使用来自一个 .py 文件的变量
【发布时间】:2021-02-24 19:04:52
【问题描述】:

我有一个如下所示的 sql_data.py 文件:

TABLE_A = '''Select * from Table_A;'''
TABLE_B = '''Select * from Table_B;'''

我有一个 main.py 文件,我想在其中循环这些变量并打印 SQL。

import sql_data

tables = ['TABLE_A', 'TABLE_B']

# this doesn't work, but this is what I am looking for.  Something dynamic like below

for table in tables:
    print(SQL_DATA.[table])

# this works, but it's hard coding in the table name which I don't want

for table in tables:
    print(SQL_DATA.TABLE_A)

有什么建议吗?

【问题讨论】:

  • 你试过SQL_DATA.[table]吗?
  • 是的,对不起。代码中有错字。我确实尝试过小写。没用。

标签: python loops variables


【解决方案1】:

您应该使用循环的变量(又名table)和getattr 来获取属性。

for table in tables:
    print(getattr(SQL_DATA, table))

【讨论】:

  • 完美,成功了。当计时器允许我时,我会接受。再次感谢
猜你喜欢
  • 1970-01-01
  • 2016-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-25
  • 2020-07-12
  • 1970-01-01
相关资源
最近更新 更多