专题1:*args和**kwargs

可变参数*args和可变参数**kwargs

(1)二者共同点:这两个参数都是表示给函数传不定数量的参数,即:我们不确定最后调用这个函数的时候会传递多少参数,也叫可变参数

(2)二者区别:

        1)*args接收不定量的非关键字参数,返回一个元组。代码如下:

def testFun(*args):
    print(type(args))
    print(args)
    for i in args:
        print(i)

testFun(1, 2, 'hello')
print('-----------')
testFun((1, 2, 'hello'))


# 输出:
<class 'tuple'>
(1, 2, 'hello')
1
2
hello
-----------
<class 'tuple'>
((1, 2, 'hello'),)
(1, 2, 'hello')
def testFun(a, b, *args):   # 注意:*args必须放在最后,否则会报错
    print(args)
    for i in args:
        print(i)
    print(a)
    print(b)

testFun(1, 2, 'hello', ['a', 'b', 'c'])


# 输出
('hello', ['a', 'b', 'c'])
hello
['a', 'b', 'c']
1
2

        2)**kwargs接收不定量的关键字参数,返回一个字典,代码如下:

def testFun(**kwargs):
    print(type(kwargs))
    print(kwargs)
    for k, v in kwargs.items():
        print(k, v)

testFun(a=1, b=2, c='hello', d=['a', 'b', 'c'])


# 输出
<class 'dict'>
{'a': 1, 'b': 2, 'c': 'hello', 'd': ['a', 'b', 'c']}
a 1
b 2
c hello
d ['a', 'b', 'c']
def testFun(x, y, **kwargs):
    print(kwargs)
    print(x)
    print(y)

testFun(1, 2, c='hello', d=[])


# 输出
{'c': 'hello', 'd': []}
1
2

 注意:在书写时,参数的顺序是:(普通参数1, 普通参数2, ..., *args, **kwargs)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值