python获取函数中参数的变量名 [英] python obtain variable name of argument in a function

查看:161
本文介绍了python获取函数中参数的变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做这样的事情:

fib = 1foo = (arg):print arg, argName # 为 arg 放入的变量的名称富(fib)

并返回:

1, fib

解决方案

你不能那样做(因为 Ignacio Vazquez-Abrams 已经回答了),但你可以用类似的方式做到:

<预><代码>>>>def foo(**kwargs):对于 kwargs 中的 arg_name:返回 kwargs[arg_name], arg_name>>>富(fib=1)(1, 'fib')

唯一的区别是必须使用关键字参数,否则将不起作用.

另一种解决方案是访问传递变量的 __name__ 属性,这将导致获得函数的名称、类或名称(或任何其他定义了该名称的名称).您唯一应该注意的是,默认情况下,这不是变量的名称,而是函数/类/模块的原始名称(定义时分配的名称).请参阅此处的示例:http://ideone.com/MzHNND

I want to do something like this:

fib = 1
foo = (arg):
    print arg, argName # the name of the variable that was put in for arg
foo(fib)

And get this returned:

1, fib

解决方案

You cannot do it like that (as Ignacio Vazquez-Abrams already answered), but you can do it in a similar way:

>>> def foo(**kwargs):
    for arg_name in kwargs:
        return kwargs[arg_name], arg_name


>>> foo(fib=1)
(1, 'fib')

The only difference is that you must use keyword arguments, otherwise it will not work.

The alternative solution is also to access __name__ attribute of passed variable, which will result in obtaining the name of function, class or name (or anything else that will have this name defined). The only thing that you should be aware of, is that by default this is not the name of the variable, but the original name of the function/class/module (the one assigned when it was being defined). See the example here: http://ideone.com/MzHNND

这篇关于python获取函数中参数的变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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