首页 > 解决方案 > 如何打印动态变量?

问题描述

我是 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'

如何返回此命令“可循环”?

希望我的描述清楚,谢谢

标签: pythonloopsclassfor-loopsyntax-error

解决方案


您可以使用(不推荐),使用(取决于上下文)eval访问局部变量,或者最好使用以下方法访问类实例变量:locals()getattrexample

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)))

推荐阅读