跟随小甲鱼up主学习Python——函数(3)

收集函数:参数用户爱传几个传几个的特性的形参,定义:在形参的名字面前加一个星号*就可。

>>> def myfunc(*args):
    print("有{}个参数。".format(len(args)))
    print("第二个参数是:{}。".format(args[1]))

    
>>> myfunc('小甲鱼', '不二入是')
有2个参数。
第二个参数是:不二入是。
>>> myfunc(1, 2, 3, 4, 5)
有5个参数。
第二个参数是:2。
>>> def myfunc(*args):
    print(args)

    
>>> myfunc(1, 2, 3, 4, 5)
(1, 2, 3, 4, 5)                          //本质是元组,元组具有打包和解包的能力
>>> def myfunc():
    return 1, 2, 3                      //返回多个值

>>> myfunc()
(1, 2, 3)
>>> x, y, z = myfunc()           //解包
>>> x
1
>>> y
2
>>> z
3

函数参数传递和元组同样道理,通过*可以实现打包操作,将多个参数打包到一个元组里面

>>> def myfunc(*args):
    print(type(args))

    
>>> myfunc(1, 2, 3, 4)
<class 'tuple'>

注:在收集参数的后面还有其他参数,这个参数只能用关键字参数来指定。

>>> def myfunc(*args, a, b):
    print(args, a, b)

    
>>> myfunc(1, 2, 3, 4, 5)
Traceback (most recent call last):
  File "<pyshell#23>", line 1, in <module>
    myfunc(1, 2, 3, 4, 5)
TypeError: myfunc() missing 2 required keyword-only arguments: 'a' and 'b'

>>> myfunc(1, 2, 3, a=4, b=5)
(1, 2, 3) 4 5

星号其实就是一个匿名的收集参数

>>> def abc(a, *, b, c):
    print(a, b, c)

    
>>> abc(1, 2, 3)
Traceback (most recent call last):
  File "<pyshell#27>", line 1, in <module>
    abc(1, 2, 3)
TypeError: abc() takes 1 positional argument but 3 were given

>>> abc(1, b=2, c=3)
1 2 3

收集参数可以将多个参数打包为元组,还可以将参数打包为字典,通过两个星号就可以打包为字典。

>>> def myfunc(**kwargs):
    print(kwargs)

    
>>> myfunc(a=1, b=2, c=3)          //字典的元素都是键值对,关键字正好是左右都有值,且有等号
{'a': 1, 'b': 2, 'c': 3}

混合起来,既有元组又有字典

>>> def myfunc(a, *b, **c):
    print(a, b, c)

    
>>> myfunc(1,2,3,4,x=5,y=6)
1 (2, 3, 4) {'x': 5, 'y': 6}

同时拥有字典和元组的函数为format()

>>> help(str.format)
Help on method_descriptor:

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

解包参数:在形参上使用星号称之为参数的打包,在实参上使用,则解包。

>>> args = (1, 2, 3, 4)
>>> def myfunc(a, b, c, d):
    print(a, b, c, d)

    
>>> myfunc(args)
Traceback (most recent call last):
  File "<pyshell#42>", line 1, in <module>
    myfunc(args)
TypeError: myfunc() missing 3 required positional arguments: 'b', 'c', and 'd'

>>> myfunc(*args)
1 2 3 4
>>> kwargs = {'a':1, 'b':2, 'c':3, 'd':4}
>>> myfunc(kwargs)
Traceback (most recent call last):
  File "<pyshell#48>", line 1, in <module>
    myfunc(kwargs)
TypeError: myfunc() missing 3 required positional arguments: 'b', 'c', and 'd'

>>> myfunc(**kwargs)
1 2 3 4

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值