搞懂function(*args,**kwargs)

时间:2021-03-16 14:31:29

给出一个例子:

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

输出结果为:

/usr/bin/python2.7 /home/alex/PycharmProjects/unittest_learn/new_confuze.py
args= (1, 2, 3, 4)
kwargs= {}
---------------------------
args= ()
kwargs= {'a': 1, 'c': 3, 'b': 2}
---------------------------
args= (1, 2, 3, 4)
kwargs= {'a': 1, 'c': 3, 'b': 2}
---------------------------
args= ('a', 1, None)
kwargs= {'a': 1, 'c': 3, 'b': ''}
--------------------------- Process finished with exit code 0