python - 如何打印动态变量?
问题描述
我是 Python 新手,我有一个问题:在我正在使用的包中,有一个命令可以通过以下方式调用:example.D1,example.D2,更改 D 后面的数字。想要创建一个循环来打印所有结果,其中 D 后面的数字从 1 到 100。
我试过了
for i in range(1, 100):
print(example.Di)
错误是raise AttributeError("'*' has no attribute '%s'" % name) AttributeError: '*' has no attribute 'Di'
如何返回此命令“可循环”?
希望我的描述清楚,谢谢
解决方案
您可以使用(不推荐),使用(取决于上下文)eval
访问局部变量,或者最好使用以下方法访问类实例变量:locals()
getattr
example
for i in range(1, 100):
print(getattr(example, 'D{0}'.format(i)))
如果你想在Di
不存在的情况下返回一个特定的值,你可以将它作为默认返回值添加到getattr
,fi 返回字符串'variable Di not found'
。
for i in range(1, 100):
print(getattr(example, 'D{0}'.format(i), 'variable D{0} not found'.format(i)))
推荐阅读
- java - 添加到授予权限后未立即执行的联系人
- python - 如何并行启动函数,检查它们是否完成,并在python中启动一个新函数?
- swift - 如何将字符串传递给 SKScene(filenamed:) 动画文件中的 SKLabelNode?
- python - 如何在 Pandas 中的 Dataframe 中正确编码 JSON 中的数据
- flutter - 如何在任何地方从另一个类调用函数
- javascript - Next Js 服务端 Api 读写 JSON
- angular - 登录后的角度重定向-> 404
- git - 从索引中删除文件后 git commit -a 如何工作
- python - Python脚本完成但进程仍然存在
- excel - 将 ADODB 查询的结果复制到工作表