函数的冗余参数

Python函数参数详解

如下,当我们定义了两个形参,那么我们传入实参的时候也只能传入两个,不能多也不能少:

#!/usr/bin/env python

def fun(x, y):
    print(x+y)

fun(2, 3)

如果我们要传多个参数可以用 *args 来处理,*args 用于接收冗余参数(冗余也就是多余的意思):

def fun(x, y, *args):
    print x
    print y
    print args

fun(1, 2, 3, 4, 5)
[root@localhost ~]$ python 1.py    # 以元组的形式返回冗余的参数
1
2
(3, 4, 5)

**kwargs 也可以用于接收冗余参数,但传参时必须以 key=value 的形式传入,且返回的是一个字典:

#!/usr/bin/env python

def fun(x, y, *args, **kwargs):
    print x
    print y
    print args
    print kwargs

fun(1, 2, 3, 4, 5, a=6, b=7)
[root@localhost ~]$ python 1.py
1
2
(3, 4, 5)
{'a': 6, 'b': 7}

 

 

 

 

 

 

 

    

转载于:https://www.cnblogs.com/pzk7788/p/10262511.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值