The difference python * args and ** kwargs of

A, * args to use

      * Args parameter used to pack into the body of a function call to a tuple

      Example 1:

 

def function(*args):
    print(args, type(args))

function(1)  #(1,) <class 'tuple'>

 

  Example 2:

 

def function(x, y, *args):
    print(x, y, args)

function(1, 2, 3, 4, 5) #1 2 (3, 4, 5)

 

Two, ** kwargs to use

      ** kwargs packaged into a dict keyword arguments to the function body calls

      Example 1:

 

def function(**kwargs):
    print( kwargs, type(kwargs))

function(a=2) #{'a': 2} <class 'dict'>

 

     Example 2:

 

def function(**kwargs):
    print(kwargs)

function(a=1, b=2, c=3)  #{'c': 3, 'b': 2, 'a': 1}

 

   

Precautions: Parameter arg, * args, ** position kwargs three parameters must be certain. It must be (arg, * args, ** kwargs) in this order, otherwise the program error.

 

def function(arg,*args,**kwargs):
    print(arg,args,kwargs)

function(6,7,8,9,a=1, b=2, c=3) #6 (7, 8, 9) {'a': 1, 'c': 3, 'b': 2}

 

def demo(*args,**kwargs):
    print(args,',,,,')
    print(kwargs,'!!!')
    print('test...')

demo(2,4,y=[2,3,4,5],k={'a':12,'b':23},f=12)

# Operating results 
' ''
(2, 4) ,,,,
{'f': 12, 'k': {'a': 12, 'b': 23}, 'y': [2, 3, 4, 5]} !!!
test...
'''

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/Kerryworld/p/11901983.html