好久沒有學習python了,應為工作的需要,再次拾起python,喚起記憶。
當函式的引數不確定時,可以使用*args 和**kwargs,*args 沒有key值,**kwargs有key值。
還是直接來**吧,廢話少說
[python]
def fun_var_args(farg, *args):
"arg:", farg
for value in args:
"another arg:", value
fun_var_args(1, "two",3) # *args可以當作可容納多個變數組成的list
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:
[python]view plain
copy
print?
arg: 1
another arg: two
another arg: 3
arg: 1
another arg: two
another arg: 3
**kwargs:
[python]view plain
copy
print?
def fun_var_kwargs(farg, **kwargs):
"arg:", farg
for key in kwargs:
"another keyword arg: %s: %s" % (key, kwargs[key])
fun_var_kwargs(farg=1, myarg2="two", myarg3=3)# myarg2和myarg3被視為key, 感覺**kwargs可以當作容納多個key和value的dictionary
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:
[python]view plain
copy
print?
arg: 1
another keyword arg: myarg2: two
another keyword arg: myarg3: 3
arg: 1
another keyword arg: myarg2: two
another keyword arg: myarg3: 3
也可以用下面的形式:
[python]view plain
copy
print?
def fun_var_args_call(arg1, arg2, arg3):
"arg1:", arg1
"arg2:", arg2
"arg3:", arg3
args = ["two", 3]#list
fun_var_args_call(1, *args)
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:
[python]view plain
copy
print?
arg1: 1
arg2: two
arg3: 3
arg1: 1
arg2: two
arg3: 3
[python]view plain
copy
print?
def fun_var_args_call(arg1, arg2, arg3):
"arg1:", arg1
"arg2:", arg2
"arg3:", arg3
kwargs = # dictionary
fun_var_args_call(1, **kwargs)
def fun_var_args_call(arg1, arg2, arg3):
print "arg1:", arg1
print "arg2:", arg2
print "arg3:", arg3
kwargs = # dictionary
fun_var_args_call(1, **kwargs)
result:
[python]view plain
copy
print?
arg1: 1
arg2:"two"
arg3:3
arg1: 1
arg2:"two"
arg3:3
python中args和kwargs引數的使用
在python中,規定了函式中的形參前帶 的,稱為可變位置引數,通常用 args表示。args表示乙個元組,傳入的引數值會被放到這個元組裡面,型別可以是任意的。同理,函式中形參前帶 的,成為可變關鍵字引數,通常用 kwargs表示。表示乙個字典,傳入的引數以鍵值對的形式存放在了字典裡面。下面我們來看...
Python中 args 和 kwargs的用法
當函式的引數不確定時,可以使用 args 和 kwargs,args 沒有key值,kwargs有key值。還是直接來 吧,廢話少說 python view plaincopyprint?def fun var args farg,args print arg farg for value in a...
Python中 args 和 kwargs的用法
好久沒有學習python了,應為工作的需要,再次拾起python,喚起記憶。當函式的引數不確定時,可以使用 args 和 kwargs,args 沒有key值,kwargs有key值。還是直接來 吧,廢話少說 python view plaincopyprint?def fun var args f...