Python - function 8, variable length parameters

Variable-length parameters: Variable-length refers to the number of actual parameters is not fixed 
. Variable-length actual parameters defined by position: *
Variable-length actual parameters defined by keyword: **

First, by position
def func(x,y,*args):
    print(x,y)
    print(args)
func( 1,2,3,4,5 )
   # *Process the extra arguments defined by position 
  # and then assign it to the last variable to save it as a tuple 
  # args=(3,4,5)
View Code

   1. Equivalent

def func(x,y,*args):
    print(x,y)
    print(args)
func( 1,2,*(3,4,5)) #Same as func(1,2,3,4,5), why is the same in the next principle
View Code

   2. Principle

def func(x,y,z):
    print(x,y,z)
func( *(1,2,3 ))
 # *==Positional parameters will split (1,2,3) 
# and assign them one by one
View Code

  2. By keyword

def func(x,y,**kwargs):
    print(x,y)
    print(kwargs)
func( 1,y=2,z=3,a=1,b=3 )
   # **Process the extra arguments defined by the keyword 
  # and then assign it to the last variable to save it in the form of a dictionary 
  # kwargs={'z':3,'a':1,'b':3}
View Code

   1. Equivalent

def func(x,y,**kwargs):
    print(x,y)
    print(kwargs)
func( 1,y=2,**{ ' a ' :1, ' b ' :3, ' z ' :3}) #with func(1,y=2,a=1,b=3,z= 3) The same, the principle is in the next item
View Code

   2. Principle

def func(x,y,z):
    print(x,y,z)
func( **{ ' y ' :2, ' x ' :1, ' z ' :3 })
 **== keyword arguments will be { ' y ' :2, ' x ' :1, ' z ' :3 } Open
 # and then assign one by one
View Code

 

 



Guess you like

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