# 在函数定义中使用*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}) # ++++++++++++++++++
时间: 2024-10-25 21:02:43