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

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。
更多推荐
所有评论(0)