python调用函数输入列表,在python中用参数列表调用一个函数

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].

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值