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}
相关文章推荐
- python装饰器:有参数的装饰器、不定长参数的装饰器、装饰有返回值的函数、通用的装饰器
- Python给函数传递不定个数的参数
- [代码笔记] python的函数定义之各种参数(必须,关键字,默认值,不定长)
- python装饰器:有参数的装饰器、不定长参数的装饰器、装饰有返回值的函数、通用的装饰器
- python_装饰器二(对有/不定长参数函数的装饰)
- Python给函数传递不定关键字的参数
- python-函数:缺省参数、不定长参数
- <Python进阶读书笔记>之(一) 函数不定参数传递
- Python 函数当中的不定参数 *args 和**kwargs 姐妹花
- Python不定参数函数
- Python函数的不定长参数
- Python 不定长函数 (函数可变参数个数)
- python-在定义函数时,不定长参数中,默认值参数不能放在必选参数前面
- python如何定义不定参数函数
- python嵌入C++------ boost.python如何在C++中调用含有不定长参数tuple变量和关键字参数dict变量的函数
- Python函数的不定长参数
- Python 函数参数的传递[转载]
- 【python学习资料】各种python 函数参数定义和解析 --转载自byte_way
- python 函数默认参数值、关键参数
- python基础教程共60课-第21课函数的参数