python变量名中有变量如何初始化及调用

您所在的位置:网站首页 python如何调用bat python变量名中有变量如何初始化及调用

python变量名中有变量如何初始化及调用

2023-03-23 10:59| 来源: 网络整理| 查看: 265

说明:因为工作原因,用的 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


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3