Python 在另一个.py文件的循环中使用一个.py文件中的变量
我有一个sql_data.py文件,如下所示:Python 在另一个.py文件的循环中使用一个.py文件中的变量,python,loops,variables,Python,Loops,Variables,我有一个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. Somethin
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)
有什么建议吗?您应该使用循环的变量(aka,
table
)和getattr
来获取属性
for table in tables:
print(getattr(SQL_DATA, table))
您是否尝试了SQL数据。[table]?是的,对不起。在代码上有输入错误。我试过小写。不管用,太好了,管用了。当计时器允许时,我将接受。再次感谢