Python是否有办法通过函数传递参数

时间:2012-03-29 00:20:51

标签: javascript python

Javascript在每个函数中都有一个构造不良但很方便的“arguments”变量,这样你就可以通过这样的函数传递参数:

function foo(a, b, c) {
    return bar.apply(this, arguments);
}
function bar(a, b, c) {
    return [a, b, c];
}
foo(2, 3, 5);    // returns [2, 3, 5]

在Python中有一种简单的方法可以做类似的事情吗?

4 个答案:

答案 0 :(得分:4)

>>> def foo(*args):
...     return args

>>> foo(1,2,3)
(1,2,3)

是你想要的吗?

答案 1 :(得分:2)

如何使用*进行参数扩展?

>>> def foo(*args):
...     return bar(*(args[:3]))
>>> def bar(a, b, c):
...     return [a, b, c]
>>> foo(1, 2, 3, 4)
[1, 2, 3]

答案 2 :(得分:1)

我认为这与你的javascript片段非常相似。它不需要您更改功能定义。

>>> def foo(a, b, c):
...   return bar(**locals())
... 
>>> def bar(a, b, c):
...   return [a, b, c]
... 
>>> foo(2,3,5)
[2, 3, 5]

请注意locals()获取所有局部变量,因此您应该在方法的开头使用它,并在声明其他变量时复制它生成的字典。或者,您可以按照this SO post中的说明使用inspect模块。

答案 3 :(得分:1)

是的,这就是我应该说的。

def foo(*args):
    return bar(*args)

您不需要使用(a,b,c)声明该函数。 bar(...)将获得foo(...)得到的任何东西。

我的另一个蹩脚的答案如下:


我非常接近回答“不,它不能轻易完成”,但有一些额外的线条,我认为它可以。 @cbrauchli使用locals()的好主意,但是因为locals()也返回局部变量,如果我们这样做

def foo(a,b,c):
    n = "foobar" # any code that declares local variables will affect locals()
    return bar(**locals())

我们将把不需要的第四个参数n传递给bar(a,b,c),我们会得到一个错误。要解决这个问题,你需要在第一行中做一些像arguments = locals()的东西,即

def foo(a, b, c):
    myargs = locals() # at this point, locals only has a,b,c
    total = a + b + c # we can do what we like until the end
    return bar(**myargs) # turn the dictionary of a,b,c into a keyword list using **
相关问题