Python中的参数
2016-05-12 14:12
501 查看
Python中的参数
1. python函数参数有多重形式:
* test(arg1,arg2,`*args`) * test(arg1,arg2,`*args`,`**kwargs`)
2. 其中比较糊弄人的是:*args
和**kwargs
*args变长的占位参数列表 -
<class 'tuple'>
**kwargs变长的键值对参数列表 -
<class 'dict'>
3. 什么是占位参数:
test(arg1,arg2)参数括弧中列出的标识符就是占位参数
*args变长占位参数是用来发送一个非键值对的可变数量的参数列表给一个函数, 可以遍历得到它
def test_var_args(f_arg, *argv): print(type(argv)) # <class 'tuple'> print("first normal arg:", f_arg) for arg in argv: print("another arg through *argv:", arg) test_var_args('yasoob', 'python', 'eggs', 'test')
4. 什么是键值对参数:
**kwargs允许你将变长度的键值对, 作为参数传递给一个函数, 说白了就是函数的参数是个dict,但是不能直接传个dict给函数,得加上前导
**解包
def test_kwarg(**kwargs): print(type(kwargs)) # <class 'dict'> for key, value in kwargs.items(): print("{0} == {1}".format(key, value)) test_kwarg(name="foo") test_kwarg(name="foo", age=26) test_kwarg(**{'name': "foo", 'age': '26'})
5. 综合看一个更复杂的例子
def test_kwarg(name, age, *args, **kwargs): print('--------------------------------------') print('all positional args:') print('name:{0}'.format(name)) print('age:{0}'.format(age)) print('\n') print('all optional positional *args:') for arg in args: print('args:{0}'.format(arg)) print('\n') print('all keywords **kwargs:') for key, value in kwargs.items(): print("{0} == {1}".format(key, value)) # 只有占位参数 test_kwarg("foo", 26) # 占位参数 + 可选占位参数 test_kwarg("foo", 26, 'opt1') # 占位参数 + 键值对参数 test_kwarg("foo", 26, kw1=100, kw2=200) # 占位参数 + 可选占位参数 + 键值对参数 test_kwarg("foo", 26, 'opt1', 'opt2', kw1=100, kw2=200) # -------------------------------------- # all positional args: # name: # foo # age: # 26 # all optional positional * args: # all keywords ** kwargs: # -------------------------------------- # all positional args: # name: # foo # age: # 26 # all optional positional * args: # args: # opt1 # all keywords ** kwargs: # -------------------------------------- # all positional args: # name: # foo # age: # 26 # all optional positional * args: # all keywords ** kwargs: # kw1 == 100 # kw2 == 200 # -------------------------------------- # all positional args: # name: # foo # age: # 26 # all optional positional * args: # args: # opt1 # args: # opt2 # all keywords ** kwargs: # kw1 == 100 # kw2 == 200
6. Note: 函数调用时,*args
, **kwargs
是可选的,但是前面的常规参数是必须的
7. over
相关文章推荐
- numpy学习笔记
- 《Python核心编程》 18.多线程编程(一)
- python3在用pip装lxml模块遇到的问题
- python中实现将普通字典dict转换为java中的treeMap
- Michael的Python笔记(二)
- python 学习笔记11(objgraph)
- python2.7 模块全局__metaclass__
- 用Python和OpenCV提取颜色直方图特征
- Python的词法分析与语法分析
- python的string模块中的Template
- python中的socket模块
- python中的socket模块
- 运维 -- Python
- python中的 json 模块使用
- python之permutations和combinations的区别
- python之permutations和combinations的区别
- leetcode(7),Contains Duplicate(python)
- error: could not create '/Library/Python/2.7/site-packages/jedi': Permission denied
- python 查看API
- WIndwos7-64bit注册