[英]Using variables from one .py file in a loop in another .py file
I have a sql_data.py file that looks like this:我有一个如下所示的 sql_data.py 文件:
TABLE_A = '''Select * from Table_A;'''
TABLE_B = '''Select * from Table_B;'''
I have a main.py file where I want to loop over those variables and print the SQL.我有一个 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)
Any suggestions?有什么建议么?
You should use the variable that you loop (aka, table
) and getattr
for getting attribute.您应该使用循环的变量(又名
table
)和getattr
来获取属性。
for table in tables:
print(getattr(SQL_DATA, table))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.