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
二、使用globals()方法hello = 123def get_variable_name(variable): loc = globals() for k,v in loc.items(): if loc[k] ==variable: return kprint(get_variable_name(hello))
输出结果:
helloProcess finished with exit code 0
推荐使用第一种方法,因为变量名存在重复可能,降低作用域范围效果更好。