博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python中*args **kwargs的使用
阅读量:4171 次
发布时间:2019-05-26

本文共 1649 字,大约阅读时间需要 5 分钟。

*args是非关键字参数,用于元组,**kwargs是关键字参数,用于字典。

1》*args

def show(*args):    print type(args)    print args    for name in args:        print name        show('song','python','c++','ping')#python将这些参数包装成一个元组,传给argsl=['song','python','c++','ping']show(*l)show(*('song','python','c++','ping'))
结果:
<type 'tuple'>
('song', 'python', 'c++', 'ping')
song
python
c++
ping
<type 'tuple'>
('song', 'python', 'c++', 'ping')
song
python
c++
ping
<type 'tuple'>
('song', 'python', 'c++', 'ping')
song
python
c++
ping

2》**kwargs

def show(**kwargs):    print type(kwargs)    print kwargs    print kwargs.items()    for item in kwargs.items():        print item        show(name='song',age=26,sex='man')#python将这些参数包装成一个字典,传给kwargsd={'name':'song','age':26,'sex':'man'}show(**d)
结果:
<type 'dict'>
{'age': 26, 'name': 'song', 'sex': 'man'}
[('age', 26), ('name', 'song'), ('sex', 'man')]
('age', 26)
('name', 'song')
('sex', 'man')
<type 'dict'>
{'age': 26, 'name': 'song', 'sex': 'man'}
[('age', 26), ('name', 'song'), ('sex', 'man')]
('age', 26)
('name', 'song')
('sex', 'man')

3》*args和**kwargs混合使用

def foo(arg,*args, **kwargs):     print 'arg = ',arg       print 'args = ', args        print 'kwargs = ', kwargs        print '------------------'if __name__ == '__main__':    foo(1,2,3)    foo(1,a=1,b=2,c=3)    foo(1,2,3,4, a=1,b=2,c=3)    foo(1,'a', 1, None, a=1, b='2', c=3)
结果:
arg =  1
args =  (2, 3)
kwargs =  {}
------------------
arg =  1
args =  ()
kwargs =  {'a': 1, 'c': 3, 'b': 2}
------------------
arg =  1
args =  (2, 3, 4)
kwargs =  {'a': 1, 'c': 3, 'b': 2}
------------------
arg =  1
args =  ('a', 1, None)
kwargs =  {'a': 1, 'c': 3, 'b': '2'}
------------------

(完)

转载地址:http://ojyai.baihongyu.com/

你可能感兴趣的文章
CodeForces - 785C Anton and Fairy Tale
查看>>
CodeForces - 831D Office Keys
查看>>
hdu 1258 确定比赛名次
查看>>
hdu 3342 拓扑,是否存在环
查看>>
poj 1860 拓扑。。
查看>>
poj 2553 The Bottom of a Graph 未完
查看>>
inux下如何统计一个目录下的文件个数以及代码总行数(转)
查看>>
Linux下 虚拟机Bochs的使用
查看>>
glib-读取配置文件
查看>>
SonarQube 静态代码检查的安装
查看>>
嵌入式Linux驱动开发的知识图谱
查看>>
Algorithm 4th environment setup
查看>>
Linux设备驱动开发基础之互斥与同步基础
查看>>
Linux驱动开发之内存管理基础
查看>>
用gitlabCI快速搭建一个GitServer与CI
查看>>
SPI Nor Flash
查看>>
ARM Linux BenchMark
查看>>
完整精确导入Kernel与Uboot参与编译了的代码到Source Insight,Understand, SlickEdit
查看>>
Freescale IMX6 Android (5): APP通过JNI控制LED
查看>>
PPT分享: Linux启动流程 关于initrd与initramfs的区分及其发展历程
查看>>