python *和**区别

0 评论
/ /
1067 阅读
/
2017 字
03 2018-07

一个星(*):表示接收的参数作为元组来处理

两个星(**):表示接收的参数作为字典来处理

-----------------------------------------------------------------------------------------------------------------------------------------
def print_everything(*args):
  for count, thing in enumerate(args):
    print '{0}.{1}'.format(count,thing)
print_everything('apple','banana','cabbage')  #参数传入元组
'''测试输出:
0.apple
1.banana
2.cabbage
'''
----------------------------------------------------------------------------------------------------------------------------------------

 

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

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

'''测试输出:
cabbage = vegetable
apple = fruit
'''

-------------------------------------------------------------------------------------------------------------------------------------

 

def foo(*args,**kwargs):
print 'args=',args
print 'kwargs=',kwargs
print '------'

test1:

>>> foo(1,2,3,4)
args= (1, 2, 3, 4)
kwargs= {}
------

test2:

foo(a=1,b=3)
args= ()
kwargs= {'a': 1, 'b': 3}
------

test3:

foo(1,'a',None,a=1,b='2',c=3)
args= (1, 'a', None)
kwargs= {'a': 1, 'c': 3, 'b': '2'}
------

test4:

foo(1,2,4,a=1,b=4)
args= (1, 2, 4)
kwargs= {'a': 1, 'b': 4}

 

可以看到,这两个是python中的可变参数。*args表示任何多个无名参数,它是一个tuple;**kwargs表示关键字参数,它是一个dict。并且同时使用*args和**kwargs时,必须*args参数列要在**kwargs前,像foo(a=1, b='2', c=3, a', 1, None, )这样调用的话,会提示语法错误“SyntaxError: non-keyword arg after keyword arg”。

知道*args和**kwargs是什么了吧。还有一个很漂亮的用法,就是创建字典:

def kw_dict(**kwargs):
return kwargs
print kw_dict(a=1,b=2,c=3) == {'a':1, 'b':2, 'c':3}
其实python中就带有dict类,使用dict(a=1,b=2,c=3)即可创建一个字典了。