程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

*args and * *kwargs in python (learning notes)

編輯:Python

Link to the original text :Python Medium *args and **kwargs(python Based on learning )_ Dandelion dust blog -CSDN Blog _**kwargs

One 、 meaning


1、*args and **kwargs It is mainly used to define the variable parameters of a function

2、*args: Send a variable number of parameter lists of non key value pairs to the function

3、**kwargs: Send a variable number of parameter lists of key value pairs to the function

4、 If you want to use a named variable inside a function ( Like a dictionary ), So use **kwargs.

The purpose of defining variable parameters is to simplify the call .

* and ** The role here : Packing parameters .

Two 、 Precautions when using


1、*args and **kwargs Not fixed , Only the front * and ** Is fixed and immutable , The following name can be changed at will , for example *vals A variable number of parameters representing non key value pairs ,**parms Represents a variable number of key value pairs . Use *args and **kwargs, It's a custom of Convention , You can also not use this name .

2、 When used at the same time *args and **kwargs when ,*args Must be written in **kwargs Before .

def test_args(*args):
print(args)
def test_kwargs(**kwargs):
print(kwargs)
print(type(kwargs))
for key, value in kwargs.items():
print("{} == {}".format(key, value))
def test_all(*args,**kwargs):
print(args)
print(kwargs)

∗ Put function test_args() Multiple parameters received 'name','age','address','sex', Packed into Tuples ('name','age','address','sex'), Assigned to the formal parameter args.

test_args('name','age','address','sex')
# ('name', 'age', 'address', 'sex')

 ** Put function test_kwargs() Multiple parameters received , With Dictionaries Is assigned to a formal parameter kwargs.

test_kwargs(name='zxf',age=23,address='zhejiang')
# {'name': 'zxf', 'age': 23, 'address': 'zhejiang'}
# <class 'dict'>
# name == zxf
# age == 23
# address == zhejiang
test_all('name','age',name='zxf',age=23)
# ('name', 'age')
# {'name': 'zxf', 'age': 23}


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved