提问人:SH Chung 提问时间:8/14/2023 最后编辑:John KugelmanSH Chung 更新时间:8/14/2023 访问量:48
使用字符串对象作为同名变量 [duplicate]
Use a string object as the variable of the same name [duplicate]
问:
tn = 'convert'
print('t'+'n')
tn
是一个字符串对象。但是我想将这个字符串对象用作同名变量。因此,我可以期望将结果声明为变量 .tn
答:
0赞
futium
8/14/2023
#1
最好避免变量变量名称;但是,如果必须的话,使用字典会好得多。
尝试这样的事情:
# create dictionary of variables
variables = {}
variables['tn'] = 'convert'
# create variable name
variable_name = 't' + 'n'
print(variables[variable_name])
正是维护和调试方面导致了恐怖。想象一下,当你的代码中没有实际更改“foo”的地方时,试图找出变量“foo”在哪里发生了变化。进一步想象一下,你必须维护的是别人的代码......
希望这会有所帮助
评论