一、使用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

推荐使用第一种方法,因为变量名存在重复可能,降低作用域范围效果更好。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐