如何在Python中获取函数的实际参数名称? [英] How to get name of function's actual parameters in Python?

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

问题描述

例如:

def func(a):
    # how to get the name "x"

x = 1
func(x)

如果使用inspect模块,则可以获取堆栈框架对象:

If I use inspect module I can get the stack frame object:

import inspect
def func(a):
    print inspect.stack()

退出:

[
(<frame object at 0x7fb973c7a988>, 'ts.py', 9, 'func', ['  stack = inspect.stack()\n'], 0)

(<frame object at 0x7fb973d74c20>, 'ts.py', 18, '<module>', ['func(x)\n'], 0)
]

或使用inspect.currentframe()我可以获取当前帧.

or use inspect.currentframe() I can get the current frame.

但是我只能通过检查功能对象来获得名称"a".

But I can only get the name "a" by inspect the function object.

使用inspect.stack我可以获得调用堆栈:"['func(x)\n']"

Use inspect.stack I can get the call stack:"['func(x)\n']",

通过解析"['func(x)\n']"调用func时,如何获取实际参数的名称(此处为"x")?

How can I get the name of actual parameters("x" here) when call the func by parsing the "['func(x)\n']"?

如果我呼叫func(x),那么我会得到"x"

If I call func(x) then I get "x"

如果我拨打func(y),则得到"y"

一个例子:

def func(a):

    # Add 1 to acttual parameter
    ...

x = 1
func(x)
print x # x expected to 2

y = 2
func(y)
print y # y expected to 3

推荐答案

查看您的评论说明,尝试这样做的原因是:

Looking at your comment explanations, the reason you are trying to do this is:

因为我要像在C ++中那样推动参考参数

Because I want to impelment Reference Parameters like in C++

您不能那样做.在python中,所有内容均按值传递,但该值是对您传递的对象的引用.现在,如果该对象是可变的(如列表),则可以对其进行修改,但是如果它是不可变的,则将创建并设置一个新对象.在您的代码示例中,x是一个不可变的int,因此,如果要更改x的值,只需从要调用的函数中返回其新值:

You can't do that. In python, everything is passed by value, but that value is a reference to the object you pass. Now, if that object is mutable (like a list), you can modify it, but if it's immutable, a new object is created and set. In your code example, x is an int which is immutable, so if you want to change the value of x it, just return its new value from the function you are invoking:

def func(a):
    b = 5 * a
    # ... some math
    return b


x = 1
x = func(x)

那么,如果要返回多个值怎么办?使用tuple

So what if you want to return multiple values? Use a tuple!

def func(a, b):
    a, b = 5 * b, 6 * a
    # ...
    return b, a

a, b = 2, 3
a, b = func(a, b)

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

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