args就是所有參數的數組,kwargs就是當你傳入key=value是存儲的字典,當函數的參數不確定時,可以使用*args 和kwargs,*args 沒有key值,kwargs有key值
def fun_var_args(farg, *args):
print "arg:", farg
for value in args:
print "another arg:", value
fun_var_args(1, "two", 3) # *args可以當作可容納多個變量組成的list
result:
arg: 1
another arg: two
another arg: 3
**kwargs:
def fun_var_kwargs(farg, **kwargs):
print "arg:", farg
for key in kwargs:
print "another keyword arg: %s: %s" % (key, kwargs[key])
fun_var_kwargs(farg=1, myarg2="two", myarg3=3) # myarg2和myarg3被視為key, 感覺**kwargs可以當作容納多個key和value的dictionary
result:
arg: 1
another keyword arg: myarg2: two
another keyword arg: myarg3: 3
也可以用下面的形式:
def fun_var_args_call(arg1, arg2, arg3):
print "arg1:", arg1
print "arg2:", arg2
print "arg3:", arg3
args = ["two", 3] #list
fun_var_args_call(1, *args)
result:
arg1: 1
arg2: two
arg3: 3
def fun_var_args_call(arg1, arg2, arg3):
print "arg1:", arg1
print "arg2:", arg2
print "arg3:", arg3
kwargs = {"arg3": 3, "arg2": "two"} # dictionary
fun_var_args_call(1, **kwargs)
result:
arg1: 1
arg2:"two"
arg3:3
當所有傳參為key=value形式將返回字典形式
下面關於Python的文章您也可能喜歡,不妨看看:
Linux下Python的安裝以及注意事項 http://www.linuxidc.com/Linux/2015-11/124861.htm
Ubuntu 14.04 下安裝使用Python rq模塊 http://www.linuxidc.com/Linux/2015-08/122441.htm
無需操作系統直接運行 Python 代碼 http://www.linuxidc.com/Linux/2015-05/117357.htm
CentOS上源碼安裝Python3.4 http://www.linuxidc.com/Linux/2015-01/111870.htm
《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm
《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm
Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm
在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm
Python 語言的發展簡史 http://www.linuxidc.com/Linux/2014-09/107206.htm
Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡