如何在Python中动态引用变量?

时间:2018-12-19 09:20:49

标签: python

我有以下代码:

PROJECT_ID = 'test'
BQ_TABLE_NAME_CATEGORIES = 'categories'
BQ_TABLE_NAME_MANUFACTURERS = 'manufacturers'
list = [BQ_TABLE_NAME_CATEGORIES, BQ_TABLE_NAME_MANUFACTURERS]
table_categories = PROJECT_ID + '.'  + BQ_TABLE_NAME_CATEGORIES
table_manufacturers = PROJECT_ID + '.' + BQ_TABLE_NAME_MANUFACTURERS

for table in list:
    ....
    source_objects=['table_{0}'.format(table)]  #reference to the correct var
    ....

但是这会将字符串放入source_objects中。我希望它引用变量(无论保存在变量中) 表示我真正想要的是等效

table = BQ_TABLE_NAME_CATEGORIES

source_objects = [ table_categories ] 

table = BQ_TABLE_NAME_MANUFACTURERS

source_objects = [ table_manufacturers ] 

2 个答案:

答案 0 :(得分:1)

您可以使用eval()函数将字符串转换为变量: read on eval

PROJECT_ID = 'test'
BQ_TABLE_NAME_CATEGORIES = 'categories'
BQ_TABLE_NAME_MANUFACTURERS = 'manufacturers'
mylist = [BQ_TABLE_NAME_CATEGORIES, BQ_TABLE_NAME_MANUFACTURERS]
table_categories = PROJECT_ID + '.'  + BQ_TABLE_NAME_CATEGORIES
table_manufacturers = PROJECT_ID + '.' + BQ_TABLE_NAME_MANUFACTURERS

for table in mylist:
    source_objects=eval('table_{0}'.format(table)) #reference to the correct var
    print source_objects

输出:

test.categories
test.manufacturers

也如评论中所述,您实际上不应覆盖列表,而应使用mylist或其他任何方法

答案 1 :(得分:1)

如果我正确理解了您的问题,则您要尝试将table_categoriestable_manufacturers的值存储在名为source_objects的列表中。 假设table_...变量是全局变量,

suffixes = [BQ_TABLE_NAME_CATEGORIES, BQ_TABLE_NAME_MANUFACTURERS]

source_objects = []
for s in suffixes:
    source_objects.append(globals['table_{0}'.append(s)])
    ...

这会让您:

>>> source_objects
['test.categories', 'test.manufacturers']

如果table_...变量不是全局变量,请使用locals()。参见https://docs.python.org/3/library/functions.html#globals