Python 不定参数函数

1. 元组形式

def test1(*args):

    print('################test1################')
    print(type(args))
    print(args)

正确调用:

test1(1, 2)          #args在函数体内部为tuple类型

错误调用:

test1(1, b=2)      #TypeError: test1() got an unexpected keyword argument 'b'
test1(a=1, b=2)  #TypeError: test1() got an unexpected keyword argument 'a'
test1(a=1, 2)      #TypeError: test1() got an unexpected keyword argument 'a'

 

2. 字典形式

def test2(**kargs):

    print('################test2################')
    print(type(kargs))
    print(kargs)

正确调

test2(a=1, b=2)  #kargs在函数体内部为dict类型

错误调用:

test2(1, 2)          #TypeError: test2() takes exactly 0 arguments (2 given)
test2(1, b=2)      #TypeError: test2() takes exactly 0 arguments (2 given)
test2(a=1, 2)      #SyntaxError: non-keyword arg after keyword arg

 

3. 混合形式

def test3(*args, **kargs):

    print('################test3################')
    print(type(args))
    print(args)
    print(type(kargs))
    print(kargs

正确调用:

test3(1, 2)          #args在函数体内部为tuple类型,kargs为空dict类型
test3(1, b=2)      #args在函数体内部为tuple类型,kargs为dict类型
test3(a=1, b=2)  #args在函数体内部为空tuple类型,kargs为dict类型

错误调用:

test3(a=1, 2)      #SyntaxError: non-keyword arg after keyword arg

 

 练习:

1 def test(num,*args,**kwargs):
2     print('---test1---%d' %num)
3     print('---test2---',args)
4     print('---test3---',kwargs)
5 
6 test(100)
7 test(100,200)
8 test(100,200,300,mm=100)

 

答案:

 1 C:\>python test.py
 2 ---test1---100
 3 ---test2--- ()
 4 ---test3--- {}
 5 
 6 ---test1---100
 7 ---test2--- (200,)
 8 ---test3--- {}
 9 
10 ---test1---100
11 ---test2--- (200, 300)
12 ---test3--- {'mm': 100}

 

转载于:https://www.cnblogs.com/liangmingshen/p/9251047.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值