python设计一个函数_Python的任意个数参数的函数设计

任意参数个数的函数是一种很方便的设计。

通过在函数定义的时候,指明*args,这个就表示函数接收任意个数参数。有*args,同时还可以有别的所谓的位置参数(positional argument),键值参数(keyword argument),可以混用。

下面是我自己写的一个学习函数,注意*args传递进来的是一个tuple:

>>>

>>> def test1(*args):

... print(args)

...

>>>

>>> test1(1,'b',6,'y',1.56)

(1, 'b', 6, 'y', 1.56)

>>>

>>> test1('kkkk')

('kkkk',)

>>>

>>>

>>> test1('kkkk',77)

('kkkk', 77)

>>>

*args的写法,重点在*,而不是args,你也可以协成*arggss,或者*kkk。反正记住,都是tuple。

函数设计时,一个*表示tuple,两个**表示dict,如下代码:

>>>

>>> def test2(**kwargs):

... print(kwargs)

...

>>>

>>> test2(k1=1,k2=2,k3=3)

{'k1': 1, 'k2': 2, 'k3': 3}

>>>

>>> test2(k4=4)

{'k4': 4}

>>>

2018-09-27:

Python中有一种叫做Unpacking Argument的操作,也可以用来理解其不定参数函数接口的设计思路,我们通过官方给出的两个代码段来学习吧:

>>> list(range(3, 6)) # normal call with separate arguments

[3, 4, 5]

>>> args = [3, 6] # args = (3, 6) is also OK

>>> list(range(*args)) # call with arguments unpacked from a list

[3, 4, 5]

#######

>>> def parrot(voltage, state='a stiff', action='voom'):

... print("-- This parrot wouldn't", action, end=' ')

... print("if you put", voltage, "volts through it.", end=' ')

... print("E's", state, "!")

...

>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}

>>> parrot(**d)

-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !

*:提取List或Tuple;

**:提取Dict。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值