python 收集参数

通过在形参的前面加上“ * ”表示:

def func(*args):
    print("There have {} members".format(len(args)))
    print("The second member is {}".format(args[1]))

func(1, 2, 3, 4)
## There have 4 members
## The second member is 2

def fun(*args):
    print(args)
fun(1, 2, 3, 4, 5)
## (1, 2, 3, 4, 5)
#通过利用元组将多个返回值打包,同时可以通过使用获取元组中每一个元素的方式将函数解包

def funa(*args):
    print(type(args))
funa(1,2,3,4,5)
## <class 'tuple'>

如果在收集参数后面还需要传入其他参数,那么在调用函数的时候就应该使用关键字参数来指定后面的参数。

def funa(*args, a, b):
    print(args, a, b)
funa(1,2,3,a=4,b=5)
## (1, 2, 3) 4 5

除了将参数打包为元组,收集参数还可以将参数打包为字典,使用“ ** ”:

def func(**kwargs):
    print(kwargs)
func(a=1, b=2, c=3)
## {'a': 1, 'b': 2, 'c': 3}

函数会自动将关键字参数拆分为键值对传递到kwargs里。

以下是收集参数的多个方法的混合使用:

def func(a, *args, **kwargs):
    print(a, args, kwargs)
func(1, 2, 3, b=2, c=3, d=4)
## 1 (2, 3) {'b': 2, 'c': 3, 'd': 4}
# 其中第一个实参传入形参a, 后面两个位置参数传入args, 最后面的三个关键字参数传入kwargs

实例:str.format()函数

首先我们先看看help下的str.format函数

Help on method_descriptor:

format(...) unbound builtins.str method
    S.format(*args, **kwargs) -> str

    Return a formatted version of S, using substitutions from args and kwargs.
    The substitutions are identified by braces ('{' and '}').

其第一个参数是元组形式的收集参数,第二个参数是字典形式的收集参数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值