Python应用技术Python已看

Python: *args && **kwargs

2020-05-03  本文已影响0人  AI秘籍

在 python 中,
*args 和 **kwargs 都代表 1个 或 多个参数的意思。
在参数传递中会见到.

当函数的参数不确定时,可以使用args和 kwargs,
其中,
args没有key值,
kwargs有key值。

args传入的参数类型为列表,元组


image.png
image.png

kwargs传入的参数类型是 dict 词典


image.png
image.png

当函数的参数不确定时,

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)
image.png
image.png

参考:

  1. https://www.cnblogs.com/shenh/p/10487626.html
  2. https://www.cnblogs.com/codeblock/p/python_args_kwargs.html
上一篇 下一篇

猜你喜欢

热点阅读