python foundation - parameters of functions

Introduction to one form participation arguments

The parameters of the function are divided into formal parameters and actual parameters, which are referred to as formal parameters and actual parameters for short:

Formal parameters are the parameters declared in parentheses when defining a function. The formal parameter is essentially a variable name, which is used to receive the value from the outside.

Argument is the value passed in parentheses when calling the function. The value can be constant, variable, expression or a combination of the three:

#1: Arguments are constants
res=my_min(1,2)

#2: Arguments are variables
a=1
b=2
res=my_min(a,b)

#3: Arguments are expressions
res=my_min(10*2,10*my_min(3,4))

#4: Arguments can be any combination of constants, variables and expressions
a=2
my_min(1,a,10*my_min(3,4))

When calling a parameterized function, the argument (value) is assigned to the formal parameter (variable name). In Python, variable names and values are only a simple binding relationship, while for functions, this binding relationship only takes effect when the function is called and is released after the call is completed.

Specific use of binary participation arguments

2.1 location parameters

Position refers to sequence. Position parameters refer to parameters defined in sequence, which need to be viewed from two perspectives:

  1. When defining a function, the formal parameters are defined in turn from left to right, which is called position formal parameters. All formal parameters defined in this form must be passed value
def register(name,age,sex): #Define location parameters: name,age,sex,All three must be passed values
    print('Name:%s Age:%s Sex:%s' %(name,age,sex))
register() #TypeError: Missing 3 position parameters 

 

  1. When calling a function, the arguments are defined in order from left to right, which is called position arguments. All the arguments defined in this form will correspond to the formal parameters one by one from left to right
def register(name,age,sex): #Define location parameters: name,age,sex,All three must be passed values
    print('Name:%s Age:%s Sex:%s' %(name,age,sex))
register() #TypeError: Missing 3 position parameters
# Relationship between formal parameter and argument:
# 1,During the call phase, the argument (variable value) is bound to the formal parameter (variable name)
# 2,This binding relationship can only be used in function bodies
# 3,The binding relationship between arguments and formal parameters takes effect when the function is called, and the binding relationship is released after the function is called

# Specific use of binary participation arguments
# 2.1 Location parameter: the parameters defined from left to right are called location parameters
# Positional parameter:In the function definition stage, the functions are defined directly from left to right"Variable name"
#        Features: it must be transferred. One more can't be transferred, and one less can't be transferred
# def func(x,y):
#     print(x,y)
# func(1,2,3)
# func(1,)

# Position argument:In the function call phase, the values passed in from left to right
#        Features: one to one correspondence with formal parameters in order

# func(1,2)
# func(2,1)

2.2 keyword parameters

When calling a function, the argument can be in the form of key=value, which is called a keyword parameter. All arguments defined in this form can be defined completely from left to right, but they can still assign values to the specified formal parameters

>>> register(sex='male',name='lili',age=18)
Name:lili Age:18 Sex:male

It should be noted that when calling a function, the argument can also be used by position or by keyword, but the keyword parameter must be guaranteed to follow the position parameter, and a formal parameter cannot be assigned repeatedly


>>> register('lili',sex='male',age=18) #Correct use
>>> register(name='lili',18,sex='male') #SyntaxError: Keyword parameters name='lili'Before position parameter 18
>>> register('lili',sex='male',age=18,name='jack') #TypeError: Formal parameter name Assigned repeatedly
# Keyword argument: in the function call phase, according to key=value Value passed in as
#       Features: pass values to a formal parameter by name, which can be completely without reference to the order
# def func(x,y):
#     print(x,y)

# func(y=2,x=1)
# func(1,2)

# Mixed use, emphasis
# 1,The location argument must be placed before the keyword argument
# func(1,y=2)
# func(y=2,1)

# 2,You cannot pass values repeatedly for the same parameter
# func(1,y=2,x=3)
# func(1,2,x=3,y=4)

2.3 default parameters

When defining a function, formal parameters have been assigned values. These formal parameters are called default parameters. When the function has multiple parameters, it is necessary to define the parameters whose values often change as position parameters, and the parameters whose values change less as default parameters. For example, write a function to register student information. If most students are male, the formal parameter sex can be defined as the default parameter

>>> def register(name,age,sex='male'): #default sex The value of is male
...     print('Name:%s Age:%s Sex:%s' %(name,age,sex))
...

The parameter sex has been assigned value when it is defined, which means that sex can not be assigned value when calling, which reduces the complexity of function call

>>> register('tom',17) #Most cases,No need for sex Value transmission,Default to male
Name:tom Age:17 Sex:male
>>> register('Lili',18,'female') #Few cases,Can be sex Value transmission female
Name:Lili Age:18 Sex:female

Note:

  1. The default parameter must be after the position parameter
  2. The value of the default parameter is assigned only once during the function definition phase
>>> x=1
>>> def foo(arg=x):
...     print(arg)
... 
>>> x=5 #Definition phase arg It has been assigned to 1. The modification here is the same as the default parameter arg It doesn't matter
>>> foo()
1
  1. The value of the default parameter should normally be set to immutable type
def foo(n,arg=[]):    
     arg.append(n)    
     return arg    
foo(1)    
[1] 
foo(2)    
[1, 2] 
foo(3)    
[1, 2, 3]

Each call adds a value to the same list on the basis of the previous one, and the modification is as follows

def foo(n,arg=None):    
     if arg is None:    
         arg=[]    
     arg.append(n)    
     return arg    
foo(1)    
[1] 
foo(2)    
[2] 
foo(3)    
[3]
# Default parameter: the parameter that has been assigned at the function definition stage is called the default parameter
#       Features: it has been assigned in the definition stage, which means that it can be assigned without assignment in the call stage
# def func(x,y=3):
#     print(x,y)
#
# # func(x=1)
# func(x=1,y=44444)


# def register(name,age,gender='male'):
#     print(name,age,gender)
#
# register('Three guns',18)
# register('Rocket Force',19)
# register('artillery',19)
# register('No gun',19,'female')


# The positional shape is mixed with the default formal parameters, emphasizing:
# 1,The default position of the parameter must be on the left
# def func(y=2,x):
#     pass

# 2,The value of the default parameter is assigned in the function definition stage. To be precise, it is given the memory address of the value
# Model 1:
# m=2
# def func(x,y=m): # Memory address of y = > 2
#     print(x,y
# m=3333333333333333333
# func(1)

# Model 2:
# m = [111111, ]
#
# def func(x, y=m): # Memory address of y = > [111111,]
#     print(x, y)
#
# m.append(3333333)
# func(1)

# 3,Although the default value can be specified as any data type, variable types are not recommended
# The most ideal state of the function: the call of the function is only related to the function itself, not affected by the external code
# m = [111111, ]
#
# def func(x, y=m):
#     print(x, y)
#
# m.append(3333333)
# m.append(444444)
# m.append(5555)
#
#
# func(1)
# func(2)
# func(3)


# def func(x,y,z,l=None):
#     if l is None:
#         l=[]
#     l.append(x)
#     l.append(y)
#     l.append(z)
#     print(l)

# func(1,2,3)
# func(4,5,6)

# new_l=[111,222]
# func(1,2,3,new_l)

2.4 variable length parameters (usage with *)

Variable parameter length means that when calling a function, the number of arguments can not be fixed, while when calling a function, the definition of arguments is nothing more than by location or keyword, which requires formal parameters to provide two solutions to deal with two forms of variable length parameters respectively

2.4.1 position parameters of variable length

If the last parameter name is preceded by a plus sign, the overflow position arguments will be received when calling the function, saved in the form of tuples and assigned to the parameter

>>> def foo(x,y,z=1,*args): #In the last parameter name args preposed*number
...     print(x)
...     print(y)
...     print(z)
...     print(args)
... 
>>> foo(1,2,3,4,5,6,7)  #Arguments 1, 2 and 3 are formal parameters by position x,y,z Assignment, redundant position arguments 4, 5, 6 and 7 are*Receive, save it in the form of tuple and assign it to args,Namely args=(4, 5, 6,7)

1
2
3
(4, 5, 6, 7)

If we generate a list in advance, we can still pass the value to * args

>>> def foo(x,y,*args):
...     print(x)
...     print(y)
...     print(args)
... 
>>> L=[3,4,5]
>>> foo(1,2,*L) # *L It is equivalent to position parameters 3, 4 and 5, foo(1,2,*L)Is equivalent to foo(1,2,3,4,5)
1
2
(3, 4, 5)

Note: if * is not added when L is passed in, L is just an ordinary position parameter

>>> foo(1,2,L) #Only one more location argument L
1
2
([1, 2, 3],)

If the formal parameter is a regular parameter (position or default), the argument can still be in the form of *

>>> def foo(x,y,z=3):
...     print(x)
...     print(y)
...     print(z)
... 
>>> foo(*[1,2]) #Equivalent to foo(1,2)
1
2
3

* args comes in handy if we want to ask for the sum of multiple values

>>> def add(*args):
...     res=0
...     for i in args:
...         res+=i
...     return res
... 
>>> add(1,2,3,4,5)
15

2.4.2 variable length keyword parameters

If the last parameter name is preceded by a plus sign, the overflow keyword parameters will be received when calling the function, saved in the form of a dictionary and assigned to the parameter

>>> def foo(x,**kwargs): #In the last parameter kwargs preposed**
...     print(x)        
...     print(kwargs)   
... 
>>> foo(y=2,x=1,z=3) #Overflow keyword argument y=2,z=3 All by**Receive, save it in the form of dictionary and assign it to kwargs
1
{'z': 3, 'y': 2}

If we generate a dictionary in advance, we can still pass the value to * * kwargs

>>> def foo(x,y,**kwargs):
...     print(x)
...     print(y)
...     print(kwargs)
... 
>>> dic={'a':1,'b':2} 
>>> foo(1,2,**dic) #**dic It is equivalent to keyword parameters a=1,b=2,foo(1,2,**dic)equivalent foo(1,2,a=1,b=2)
1
2
{'a': 1, 'b': 2}

Note: if * * is not added when dic is passed in, dic is just an ordinary location parameter

>>> foo(1,2,dic) #TypeError:function foo Only 2 position parameters are required, but 3 are transmitted

If the formal parameter is a general parameter (position or default), the argument can still be in the form of * *

>>> def foo(x,y,z=3):
...     print(x)
...     print(y)
...     print(z)
... 
>>> foo(**{'x':1,'y':2}) #Equivalent to foo(y=2,x=1)
1
2
3

If we want to write a user authentication function, it may only be based on the authentication of user name and password at first. We can use * * kwargs to provide a good environment for future expansion while maintaining the simplicity of the function.

>>> def auth(user,password,**kwargs): 
...     pass 
...
# I: *Formal parameter name: used to receive the overflow location argument. The overflow location argument will be deleted*Save the format into a meta group, and then assign the formal parameter name immediately after it
#           *It can be followed by any name, but by convention it should be args

# def func(x,y,*z): # z =(3,4,5,6)
#     print(x,y,z)

# func(1,2,3,4,5,6)

# def my_sum(*args):
#     res=0
#     for item in args:
#         res+=item
#     return res
#
# res=my_sum(1,2,3,4,)
# print(res)

# II: *Can be used in arguments with*,before*The resulting values are scattered into positional arguments
# def func(x,y,z):
#     print(x,y,z)
#
# # func(*[11,22,33]) # func(11,22,33)
# # func(*[11,22]) # func(11,22)
#
# l=[11,22,33]
# func(*l)

# III: Both formal parameters and arguments have*
# def func(x,y,*args): # args=(3,4,5,6)
#     print(x,y,args)

# func(1,2,[3,4,5,6])
# func(1,2,*[3,4,5,6]) # func(1,2,3,4,5,6)
# func(*'hello') # func('h','e','l','l','o')

Variable length keyword parameters
# I: **Formal parameter name: used to receive overflow keyword arguments,**The overflow keyword argument is saved in dictionary format, and then assigned to the following formal parameter name
#           **It can be followed by any name, but by convention it should be kwargs
# def func(x,y,**kwargs):
#     print(x,y,kwargs)
#
# func(1,y=2,a=1,b=2,c=3)

# II: **Can be used in arguments(**It can only be followed by a dictionary),Argument median**,before**After the keyword value of the argument is scattered
# def func(x,y,z):
#     print(x,y,z)

# func(*{'x':1,'y':2,'z':3}) # func('x','y','z')
# func(**{'x':1,'y':2,'z':3}) # func(x=1,y=2,z=3)

# error
# func(**{'x':1,'y':2,}) # func(x=1,y=2)
# func(**{'x':1,'a':2,'z':3}) # func(x=1,a=2,z=3)


# III: Both formal parameters and arguments have**
# def func(x,y,**kwargs):
#     print(x,y,kwargs)

# func(y=222,x=111,a=333,b=444)
# func(**{'y':222,'x':111,'a':333,'b':4444})


# Mixed use*And**: *args Must be**kwargs before
# def func(x,*args,**kwargs):
#     print(args)
#     print(kwargs)
#
# func(1,2,3,4,5,6,7,8,x=1,y=2,z=3)


def index(x, y, z):
    print('index=>>> ', x, y, z)


def wrapper(*args, **kwargs):  # args=(1,) kwargs={'z':3,'y':2}
    index(*args, **kwargs)
    # index(*(1,),**{'z':3,'y':2})
    # index(1,z=3,y=2)


wrapper(1, z=3, y=2)  # by wrapper The parameter passed is to index Useful
# Original format--->Summary----->Return to the original shape

2.5 named keyword parameters

After the * * kwargs parameter is defined, the function caller can pass in any keyword parameter key=value. If the execution of the function body code needs to rely on a key, it must be judged in the function

>>> def register(name,age,**kwargs):
...     if 'sex' in kwargs:
...         #have sex parameter
...         pass
...     if 'height' in kwargs:
...         #have height parameter
...         pass
...

To qualify a function, the caller must pass a value in the form of key=value. Python 3 provides a special syntax: when defining a formal parameter, it needs to be used as a separator, and the formal parameter after the sign is called a named keyword parameter. For such parameters, when calling a function, the value must be passed in the form of key=value, and the value must be passed

>>> def register(name,age,*,sex,height): #sex,height Name keyword parameters for
...     pass
... 
>>> register('lili',18,sex='male',height='1.8m') #Correct use
>>> register('lili',18,'male','1.8m') # TypeError:Unused keywords are in the form of sex and height Value transmission
>>> register('lili',18,height='1.8m') # TypeError There are no named keyword parameters for height Pass value.

Named keyword parameters can also have default values to simplify calls

>>> def register(name,age,*,sex='male',height):
...     print('Name:%s,Age:%s,Sex:%s,Height:%s' %(name,age,sex,height))
... 
>>> register('lili',18,height='1.8m')
Name:lili,Age:18,Sex:male,Height:1.8m

It should be emphasized that sex is not the default parameter and height is not the location parameter. Because both are in the back, they are named keyword parameters. The formal parameter sex = 'male' belongs to the default value of named keyword parameters, so there will be no problem even before the formal parameter height. In addition, if there is already an args in the formal parameter, the named keyword parameter no longer needs a separate * as the separator

>>> def register(name,age,*args,sex='male',height):
...   print('Name:%s,Age:%s,Args:%s,Sex:%s,Height:%s' %(name,age,args,sex,height))
... 
>>> register('lili',18,1,2,3,height='1.8m') #sex And height Still named keyword parameter
Name:lili,Age:18,Args:(1, 2, 3),Sex:male,Height:1.8m

 

# Named keyword parameters (understand)
#  Named keyword parameter: when defining a function,*The parameters defined later, as shown below, are called named keyword parameters
# characteristic:
# 1,Named keyword arguments must follow key=value The form of is its value transfer
# def func(x,y,*,a,b): # Among them, a and b are called named keyword parameters
#     print(x,y)
#     print(a,b)
#
# # func(1,2,b=222,a=111)

# Examples
# def func(x,y,*,a=11111,b):
#     print(x,y)
#     print(a,b)
#
# func(1,2,b=22222)

 

2.6 combined use

To sum up, all parameters can be used in any combination, but the definition order must be: location parameters, default parameters, args, named keyword parameters, * kwargs

Variable parameter * args and keyword parameter kwargs are usually used together. If the formal parameters of a function are * args and kwargs, it means that the function can receive parameters of any form and length

>>> def wrapper(*args,**kwargs):
...     pass
...

Within this function, you can also pass the received parameters to another function (which is very useful in the implementation of the decorator in section 4.6)

>>> def func(x,y,z):
...     print(x,y,z)
... 
>>> def wrapper(*args,**kwargs):
...     func(*args,**kwargs)
...
>>> wrapper(1,z=3,y=2)
1 2 3

According to the above description, when passing parameters to function wrapper, it actually follows the parameter rules of function func. The process of calling function wrapper is analyzed as follows:

  1. The position argument 1 is received, saved in tuple form and assigned to args, that is, args=(1,), the keyword argument z=3, y=2 is * received, saved in dictionary form and assigned to kwargs, that is, kwargs = {y ': 2,' Z ': 3}
  2. Execute func(args,kwargs), that is, func((1,),* {'y': 2, 'z': 3}), which is equivalent to func(1,z=3,y=2)
Tip: * args, args and kwargs in * * args and * * kwargs are replaced with other names. There is no syntax error, but it is a convention to use args and kwargs
# 2. Combined use (understand)
# Order of parameter mixing: position, new parameter, default parameter,*args,Named keyword parameters,**kwargs
# def func(x,y=111,*args,z,**kwargs):
#     print(x)
#     print(y)
#     print(args)
#     print(z)
#     print(kwargs)
#


# Order of mixed arguments:
def func(x,y,z,a,b,c):
    print(x)
    print(y)
    print(z)
    print(a)
    print(b)
    print(c)

# func(111,y=222,*[333,444],**{'b':555,'c':666})
# func(111,y=222,333,444,b=555,c=666)

# func(111,*[333,444],a=222,**{'b':555,'c':666})
# func(111,333,444,a=222,b=555,c=66)

# func(111,*[333,444],**{'b':555,'c':666},a=222,)
func(111,3333,4444,b=555,c=666,a=222)


# func(1)
# func(x=1)
# func(1,x=1)
# func(*'hello')
# func(**{})
# func(*'hell',**{})

Tags: Python

Posted by onedumbcoder on Mon, 02 May 2022 04:38:58 +0300