您的位置:首页 > 编程语言 > Python开发

Python 不定参数函数

2018-07-01 19:39 726 查看

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}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: