[英]Does Python have a way to pass arguments through a function
Javascript has a poorly constructed but convenient "arguments" variable inside every function, such that you can pass arguments through a function like so: 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]
Is there an easy way to do a similar thing in Python? 有没有一种简单的方法在Python中做类似的事情?
>>> def foo(*args):
... return args
>>> foo(1,2,3)
(1,2,3)
is that what you want? 那是你要的吗?
How about using * for argument expansion? 使用*进行参数扩展怎么样?
>>> def foo(*args):
... return bar(*(args[:3]))
>>> def bar(a, b, c):
... return [a, b, c]
>>> foo(1, 2, 3, 4)
[1, 2, 3]
I think this most closely resembles your javascript snippet. 我认为这最类似于你的javascript片段。 It doesn't require you to change the function definition.
它不需要您更改功能定义。
>>> def foo(a, b, c):
... return bar(**locals())
...
>>> def bar(a, b, c):
... return [a, b, c]
...
>>> foo(2,3,5)
[2, 3, 5]
Note that locals()
gets all of the local variables, so you should use it at the beginning of the method and make a copy of the dictionary it produces if you declare other variables. 请注意,
locals()
获取所有局部变量,因此您应该在方法的开头使用它,并在声明其他变量时复制它生成的字典。 Or you can use the inspect
module as explained in this SO post . 或者您可以使用
inspect
模块,如本SO帖子中所述 。
Yeah, this is what I should have said. 是的,这就是我应该说的。
def foo(*args):
return bar(*args)
You don't need to declare the function with (a,b,c). 您不需要使用(a,b,c)声明该函数。 bar(...) will get whatever foo(...) gets.
bar(...)将获得foo(...)得到的任何东西。
My other crummier answer is below: 我的另一个蹩脚的答案如下:
I was so close to answering "No, it can't easily be done" but with a few extra lines, I think it can. 我非常接近回答“不,它不能轻易完成”,但有一些额外的线,我认为它可以。 @cbrauchli great idea using locals(), but since locals() also returns local variables, if we do
@cbrauchli使用locals()的好主意,但是因为locals()也返回局部变量,如果我们这样做的话
def foo(a,b,c):
n = "foobar" # any code that declares local variables will affect locals()
return bar(**locals())
we'll be passing an unwanted 4th argument, n, to bar(a,b,c) and we'll get an error. 我们将把不需要的第四个参数n传递给bar(a,b,c),我们会得到一个错误。 To solve this, you'd want to do something like arguments = locals() in the very first line ie
要解决这个问题,你需要在第一行中执行类似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 **
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.