Python中*args和**kwargs 的簡單使用

xie仗劍天涯發表於2017-03-20

# 在函式定義中使用*args和kwargs傳遞可變長引數. *args用作傳遞非命名鍵值可變長引數列表(位置引數); kwargs用作傳遞鍵值可變長引數列表
# *args表示任何多個無名引數,它是一個tuple
# **kwargs表示關鍵字引數,它是一個dict

# 注:同時使用*args和**kwargs時,*args引數列必須要在**kwargs前

# eg _v1

def func(f,*args):
print ("formal arg:",f)
for f in args:
print ("another arg",f)

func(1,2,3,4)

# ('formal arg:', 1)
# ('another arg', 2)
# ('another arg', 3)
# ('another arg', 4)

# eg _v2

def functions(farg, **kwargs):
print ("farmal arg:",farg)
for key in kwargs:
print ("another keyword arg:%s: %s" % (key, kwargs[key]))

functions(farg=1,myarg2=2,myarg3=3,myarg4=4)
# ('farmal arg:', 1)
# another keyword arg:myarg4: 4
# another keyword arg:myarg2: 2
# another keyword arg:myarg3: 3

# eg_v3

def functions(*args,**kwargs):
print ("args= ",args)
print ("kwargs= ",kwargs)
print ("+"*18)

if __name__ == "__main__":
functions(1,2,3,4,5)
# ('args= ', (1, 2, 3, 4, 5))
# ('kwargs= ', {})
# ++++++++++++++++++
functions(a=1,b=2,c=3,d=4)
# ('args= ', ())
# ('kwargs= ', {'a': 1, 'c': 3, 'b': 2, 'd': 4})
# ++++++++++++++++++
functions(1,2,3,a=1,b=2,c=3)
# ('args= ', (1, 2, 3))
# ('kwargs= ', {'a': 1, 'c': 3, 'b': 2})
# ++++++++++++++++++

相關文章