说明:因为工作原因,用的 python2
今天写python脚本,需要把配置文件中的几十个id作为名称,新建list,因此需要批量的建立以及调用。
方法如下:
利用python自带的getattr
和setattr
方法
class TestService(object):
def __init__(self):
app_id_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for app_id in app_id_list:
setattr(self, 'records_list_%s' % app_id, []) # 初始化
getattr(self, 'records_list_%s' % app_id).append(app_id) # 存入相应的app_id
print("appid%s: " % app_id, getattr(self, 'records_list_%s' % app_id))
输出结果如下:
a = TestService()
('appid1: ', [1])
('appid2: ', [2])
('appid3: ', [3])
('appid4: ', [4])
('appid5: ', [5])
('appid6: ', [6])
('appid7: ', [7])
('appid8: ', [8])
('appid9: ', [9])
('appid10: ', [10])
另外,如果仅仅为了批量初始化list,也可以用这种方法
for app_id in app_id_list:
exec 'records_list_%s = []' % app_id