Python的星号(*、**)的作用
来源:互联网 发布:会计核算软件 编辑:程序博客网 时间:2024/05/20 10:56
转载自:http://blog.csdn.net/liuxingen/article/details/50113923
1. 函数的可变参数
当函数的参数前面有一个星号的时候表示这是一个可变的位置参数,两个星号*表示是可变的关键字参数。
#!env python#coding=utf-8#def foo(*args, **kwarg): for item in args: print item for k,v in kwarg.items(): print k,v print 30*'='if __name__ == '__main__': foo(1, 2, 3, a=4, b=5) foo(2, 3, a=4, b=5, c=1)
输出如下:
123a 4b 5==============================23a 4c 1b 5==============================
这样我们可以传入任意个数的参数。
2. unpack参数
星号*把序列/集合解包(unpack)成位置参数,两个星号**把字典解包成关键字参数。下面通过示例来进一步加深理解:
#!env python#coding=utf-8def foo(*args, **kwarg): for item in args: print item for k,v in kwarg.items(): print k,v print 30*'='if __name__ == '__main__': #foo(1, 2, 3, a=4, b=5) #foo(2, 3, a=4, b=5, c=1) v = (1, 2, 4) v2 = [11, 15, 23] d = {'a':1, 'b':12} foo(v, d) foo(*v, **d) foo(v2, d) foo(*v2, **d)
输出如下:
(1, 2, 4){'a': 1, 'b': 12}==============================124a 1b 12==============================[11, 15, 23]{'a': 1, 'b': 12}==============================111523a 1b 12==============================
上面的示例中如果v、v2、d没有加星号那么就当成了一个参数传递给了函数,如果加了星号那么就会解包后传递给函数。foo(*d, **d)等价于foo(1, 2, 4, a=1, b=12)。
3. 几个注意点
可变位置参数*args是一个元组,是不可修改的。
>>> def foo(*args):... args[0] = 5... >>> foo(1, 2, 3)Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in fooTypeError: 'tuple' object does not support item assignment>>> l = [1, 2, 3]>>> foo(*l)Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in fooTypeError: 'tuple' object does not support item assignment
无论我们怎么传入参数,args都是一个tuple类型,不能进行修改。
对于字典类型的如果只使用一个型号*那么传入的只是字典的键。
>>> def foo2(*args, **kwarg):... print args, kwarg... >>> d = {'a':1, 'b':2, 'c':3}>>> foo2(*d)('a', 'c', 'b') {}>>> foo2(**d)() {'a': 1, 'c': 3, 'b': 2}
阅读全文
0 0
- Python的星号(*、**)的作用
- Python的星号(*、**)的作用
- Python的星号(*、**)的作用
- Python星号操作符的作用
- ruby中星号(*)的作用
- python中带星号/一个星号/两个星号的参数
- python中带星号/一个星号/两个星号的参数
- python中带星号/一个星号/两个星号的参数
- Python 星号(*)操作符的用法
- python中神奇的星号
- CSS中星号*的特殊作用
- ognl # % 的作用(井号,星号,百分号)
- ognl # % 的作用(井号,星号,百分号)
- ognl # % 的作用(井号,星号,百分号)
- python参数—星号作用
- python的星号(*)和双星号(**)用法
- Python 参数知识(变量前加星号的意义)
- Python 参数知识(变量前加星号的意义)
- 微信公众号网页支付
- 重复内容如何影响搜索引擎优化?
- It's time for the first article
- 欢迎使用CSDN-markdown编辑器
- 基础学习(二)
- Python的星号(*、**)的作用
- 剑指offer——35.数组中的逆序对
- C#用Graphics书写文字时计算字符串所占的像素单位大小
- [Java--加密算法]--base64加密的算法实现
- Navicat实现Mysql手动备份与自动备份
- 深度搜索DFS-Lake Counting(POJ NO.2386)
- URI类与URL类概述与实例
- 12. Integer to Roman
- spring-retry简单例子