[Python进阶]001.不定参数

不定参数


介绍

  • 不定参数用 *** 定义
  • 不定参数必须在其他所有参数之后
  • 例子:os.path.join 方法就可以写入不定数量的参数

元组参数

  • 定义:*args*作为参数前缀
  • 会将传入的多个参数作为一个元组传入

代码

def fun(*args):
    for i in args:
        print i

fun('a', 'b', 'c', 'd')

def fun2(arg1, arg2, *args):        # 带2个固定参数
    print 'arg1:', arg1
    print 'arg2:', arg2
    print 'args:', args

fun2('a', 'b', 'c', 'd', 'e')

字典参数

  • 定义:**kwargs**作为参数前缀
  • 会将传入的多个参数作为一个字典传入

代码

def fun(**kwargs):
    for key in kwargs:
        print key, kwargs[key]

fun(a='arg1', b='arg2')

混合

代码

def fun(arg1, arg2, *args, **kwargs):
    print args
    print kwargs

fun('a', 'b', 'c', 'd', key1='e', key2='f')

[Python进阶]001.不定参数

本站文章为 宝宝巴士 SD.Team 原创,转载务必在明显处注明:(作者官方网站: 宝宝巴士 )

转载自【宝宝巴士SuperDo团队】 原文链接: http://www.cnblogs.com/superdo/p/4774247.html