*args and **kwargs usage of python3 advanced

  *args and **kwargs are mainly used for function definitions. You can pass an indefinite number of arguments to a function. Uncertain means: you don't know in advance how many parameters the function user will pass to you, so use these two keywords in this scenario. In fact, it is not necessary to write *args and **kwargs.  *(asterisk) is required. You can also write *ar and **k . Writing *args and **kwargs is just a popular naming convention.

 

  There are two ways to pass arguments to python functions: 
positional arguments 
and keyword arguments.

 

The difference between *args and **kwargs, both are variable parameters in python. 
    *args represents any number of unnamed parameters, which is essentially a tuple; 
    **kwargs represents keyword arguments, which is essentially a dict; 

 

  If you use *args and **kwargs at the same time, the *args parameter must be listed before **kwargs.

 

Example 1.

def fun(*args,**kwargs):

    print('args=', args)

    print('kwargs=',kwargs)

fun(1,2,3,4,A='a',B='b',C='c',D='d')

output:

args= (1, 2, 3, 4)

kwargs= {'A': 'a', 'B': 'b', 'C': 'c', 'D': 'd'}

 

Example 2:

def mutil(name,*ar): 
print(name,"Hello, master")
for item in ar:
print("My name is:",item)

mutil("liuhu","xiaoyun","liuwei" )
# liuhu master, hello
# My name is: xiaoyun
# My name is: liuwei

Example 3:
def love(**kwargs): 
for key,value in kwargs.items():
print("{0}loves{1}".format(key,value))
love(name="liuhu",age=18 )
# name loves liuhu
# age loves 18


Example 4:
def test(arg1, arg2, arg3):
print("arg1:", arg1)
print("arg2:", arg2)
print("arg3:", arg3)

args = ("two", 3, 5)
test(*args)
kwargs = {"arg3": 3, "arg2": "two", "arg1": 5}
test(**kwargs)
# arg1: two
# arg2: 3
# arg3: 5

# arg1: 5
# arg2: two
# arg3: 3


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324729853&siteId=291194637
Recommended