在python中用参数列表调用一个函数 [英] Call a function with argument list in python

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

问题描述

我试图在python中调用另一个函数内的函数,但找不到正确的语法。我想做的是这样的:
$ b

  def wrapper(func,args):
func(args)

def func1(x):
print(x)

def func2(x,y,z):
return x + y + z
$ b wrapper(func1,[x])
wrapper(func2,[x,y,z])

在这种情况下,第一个电话将工作,第二个不会。
我想修改的是包装函数,而不是被调用的函数。

解决方案

其他答案:

在行中:

  def wrapper(func ,* args):

args 意味着将剩下的参数放在一个名为 args 的列表中。



在该行中:

  func(* args)

此处<* c $ c> args 旁边的*代表take this



所以你可以做下面的事情:

  def wrapper1(func,* args):#with star 
func(* args)

def wrapper2(func,args):#without明星
func(* args)

def func2(x,y,z):
print x + y + z

wrapper1(func2, 1,2,3)
wrapper2(func2,[1,2,3])

wrapper2 中,列表显式传递,但是在两个包装中 args 包含列表 [1,2,3]


I'm trying to call a function inside another function in python, but can't find the right syntax. What I want to do is something like this:

def wrapper(func, args):
    func(args)

def func1(x):
    print(x)

def func2(x, y, z):
    return x+y+z

wrapper(func1, [x])
wrapper(func2, [x, y, z])

In this case first call will work, and second won't. What I want to modify is the wrapper function and not the called functions.

解决方案

To expand a little on the other answers:

In the line:

def wrapper(func, *args):

The * next to args means "take the rest of the parameters given and put them in a list called args".

In the line:

    func(*args)

The * next to args here means "take this list called args and 'unwrap' it into the rest of the parameters.

So you can do the following:

def wrapper1(func, *args): # with star
    func(*args)

def wrapper2(func, args): # without star
    func(*args)

def func2(x, y, z):
    print x+y+z

wrapper1(func2, 1, 2, 3)
wrapper2(func2, [1, 2, 3])

In wrapper2, the list is passed explicitly, but in both wrappers args contains the list [1,2,3].

这篇关于在python中用参数列表调用一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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