Python *args **kwargs

Python中 *args用于接收不定数量的位置参数,**kwargs用于接收不定数量的关键字参数

  • *args接收到的数据格式是元组,如果要传递的是整体的列表数据,在传递参数的时候用*[] 传递,
  • **kwargs 接收到的是字典数据

args

def print_everything(*args):
    for count, thing in enumerate(args):
        print('{0}. {1}'.format(count, thing))

print_everything('apple', 'banana', 'cabbage','aaa','asdf')

结果:

  1. banana
  2. cabbage
  3. aaa
  4. asdf

args的数据是 ('apple', 'banana', 'cabbage', 'aaa', 'asdf')

使用枚举把args转换成enumerate:

    for i in enumerate(args):
        print(i)

结果:
(0, 'apple')
(1, 'banana')
(2, 'cabbage')
(3, 'aaa')

传入参数

def func(*args):
    print(args)

func(*[1,2,3])  # 元组数据也可

kwargs

def table_things(**kwargs):
    for name, value in kwargs.items():
        print( '{0} = {1}'.format(name, value))

table_things(apple = 'fruit', cabbage = 'vegetable')

通过dict.items() 分别把字典中的key 和value 取出

参考:
http://www.cnblogs.com/yanhongjun/p/5825351.html
https://stackoverflow.com/questions/3394835/args-and-kwargs

posted @ 2017-08-24 16:05  hzxPeter  阅读(1056)  评论(0)    收藏  举报