Python:如何获取参数的名称运行时 [英] Python: How to get argument's name runtime

查看:22
本文介绍了Python:如何获取参数的名称运行时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python中:可能很明显,:)无论如何,我们正在寻找?,下面:

in Python: may be so obvious, :) anyway, we are looking for ?, below:

def printname(x):
   print ?,x

>>> a = 1.3
>>> printname(a)
>>> 'a',1.3

所以用一些东西代替 ? 来表示传递的参数的名称.
如果不是那么明显?任何技巧或解决方案?

so something instead of ? to represent the name of passed argument.
if not that obvious ? any trick or solution?

推荐答案

这并非不可能.您需要遍历备份堆栈帧并找到调用该函数的代码行.

It's not impossible. You need to traverse back up stack frames and find the line of code that calls the function.

这是一个很好的调试方法,但我不会在实际代码中使用它

It's an ok hack to do for debugging, but no way I would use it in real code

这是您的起点:

import inspect
def printname(x):
    print inspect.stack()[1][4]

a = 1.3
printname(a)

这篇关于Python:如何获取参数的名称运行时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆