我正在尝试使用自己的其他人的代码,特别是,我想从他的工作表中获取变量值,但我不会马上知道变量名。
假设他的脚本A.py包含以下内容:
test_1 = "This is the first test"
test_2 = "This is the second test"
在我可以称为B.py的脚本中,我具有以下内容:
import A
answer = A.test_1
print(answer)
这将打印出:
This is the first test
在此示例中,我遇到的问题是我不知道是1还是2,因此我想在知道所需数字后通过创建新变量来根据需要动态添加它。
x = 1
new_var = "test_" + str(x)
但是,我不能再调用他的变量了
answer = A.new_var
print(answer)
现在,这将导致AttributError:模块“ A”没有属性“ new_var”
如果尝试这种方式,我将收到语法错误:
answer = A."test_" + str(x)
有人知道我该如何解决吗?
尝试:
getattr(A, new_var)
这与A.test_ {x}相同
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句