1,前言:一般出現*args 和 **kwargs,首先給我想到的是C語言的指針,真的。估計這是用C編寫Python沒有有閹割干凈的緣故。
2,正題: 什么時候用這兩個參數呢,我們通常見得最多的時候是作為函數的參數,當函數的參數不確定時,可以使用*args和 **kwargs,*args 沒有key值,**kwargs 有key值。
3,例子
def args_test(param1,*args):
print "first param is:",param1
index = 1
for value in args:
print "the "+str(index)+" is:"+str(value)
index += 1
def kwargs_test(param1,**kwargs):
print "the first param is: ",param1
for key in kwargs:
print "the key is: %s, and the value is: %s" %(key,kwargs[key])
if __name__ == "__main__":
args_test('ha',1,'a','b','d','test')
kwargs_test('hi,kwargs',tom = 30,lilei = 28,hamei = 29)
程序結果:
first param is: ha
the 1 is:1
the 2 is:a
the 3 is:b
the 4 is:d
the 5 is:test
the first param is: hi,kwargs
the key is: lilei, and the value is: 28
the key is: hamei, and the value is: 29
the key is: tom, and the value is: 30