python获取变量名
一、使用locals()方法hello = 123loc = locals()def get_variable_name(variable):for k,v in loc.items():if loc[k] ==variable:return kprint(get_variable_name(hello))输出结果:helloProcess finished with exit code 0二、使
·
一、使用locals()方法
hello = 123
loc = locals()
def get_variable_name(variable):
for k,v in loc.items():
if loc[k] ==variable:
return k
print(get_variable_name(hello))
输出结果:
hello
Process finished with exit code 0
二、使用globals()方法
hello = 123
def get_variable_name(variable):
loc = globals()
for k,v in loc.items():
if loc[k] ==variable:
return k
print(get_variable_name(hello))
输出结果:
hello
Process finished with exit code 0
推荐使用第一种方法,因为变量名存在重复可能,降低作用域范围效果更好。
更多推荐
已为社区贡献1条内容
所有评论(0)