2012-03-29 64 views
2

的Javascript一个制作粗糙的,但方便的“论据”各项功能,这样你可以通过函数传递参数,像这样的内部变量:确实的Python有办法通过函数传递参数

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中做类似事情的简单方法?

回答

1

是的,这是我应该说的。

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

您不需要用(a,b,c)声明函数。酒吧(...)将获得任何foo(...)获得。

我的其他crummier的回答是以下:


我是如此接近回答“不,这不容易做到”,但有一些多余的线条,我觉得还可以。 @cbrauchli伟大的想法用当地人(),但由于当地人()也返回局部变量,如果我们做

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

我们将传递一个不想要的第四个参数,N,吧(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 ** 
+0

当@ andrew的一个更简单,更多Pythonic并且直截了当时,这个答案是如何被接受的? – ereOn 2014-05-22 06:10:32

+0

我真的很惊讶自己。 – pagga 2015-03-10 06:02:19

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

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

是你想要的吗?

+0

Python的'* args'功能的行为就像'spread'和'rest'接下来的JavaScript标准化。 – 2012-03-29 00:40:01

+2

也可用于风格'foo(a = 1,b = 2)'的关键词词组'',您可以使用'**'关键字扩展:'foo(** kwargs)'来捕获它们,这可以让kwargs成为'dict'任何字典都可以通过'bar(** kwargs)' – 2012-03-29 01:04:03

+0

作为关键字参数发送到另一个函数,您还可以混合匹配:'foo(a,b,* args)'或'foo(a,b = None, ** kargs)'或甚至在python 3中,'foo(a,b,* args,c = None,** kargs)' – 2012-03-29 01:08:42

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] 
+0

这几乎是我想要的,但我必须在定义中使用* args - 我不能这样做: 'def foo(a,b,c): return bar(*(args [:3]))' – futuraprime 2012-03-29 00:45:10

+0

我能想到的唯一事情就是使用locals()在foo里。 'locals()。values()'会给你所有传递给foo的参数,但它们不会保持一致。 – 2012-03-29 02:01:11

+0

@futuraprime其实,从头开始。它们将基于参数名称的一致顺序(也就是说,只要您的参数被命名为a,b和c,它们的值将以相同的顺序出现)。但是,在“a,b,c”的情况下,您可以按照“a,c,b”的顺序获取值。似乎这不值得麻烦。 – 2012-03-29 02:20:44

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()得到所有的局部变量,所以你应该在方法的开始使用它,让你声明其他变量它产生的字典的副本。或者,您可以使用inspect模块,如this SO post中所述。