A brief discussion on parameter passing of functions in Python

不言
Release: 2018-05-16 15:45:17
Original
1702 people have browsed it

1. Ordinary parameter passing

>>> def add(a,b): 
  return a+b 
 
>>> print add(1,2) 
3
>>> print add('abc','123') 
abc123
Copy after login

2. The number of parameters is optional, and the parameters are passed with default values ​​

>>> def myjoin(string,sep='_'): 
  return sep.join(string) 
 
>>> myjoin('Test') 
'T_e_s_t'
>>> myjoin('Test',';') 
'T;e;s;t' 
?
>>> def myrange(start=0,stop,step=1): 
  print stop,start,step 
   
SyntaxError: non-default argument follows default argument
Copy after login

The default value of parameter sep is '_' If this parameter is not given a value, the default value will be used. If it is given, the given value will be used

It should be noted that if a parameter is an optional parameter, then all the parameters following it should be optional. In addition, If the order of the optional parameters is reversed, the corresponding parameters can still be correctly assigned, but the variable name and value must be clearly specified

3. Number of variable parameters

>>> def printf(fmt,*arg): 
  print fmt%arg 
 
   
>>> printf ('%d is larger than %d',2,1) 
2 is larger than 1
Copy after login

The *arg in the function must be the last parameter, * means any number of parameters, *arg will put all the parameters except the previous ones into one The tuple is passed to the function and can be accessed through arg in the function

arg is a tuple, and arg can be accessed in the function through the method of accessing tuple

Another way to pass any number Parameters are passed through dictionary and can also accept multiple parameters, but each parameter needs to specify the name correspondence, such as a=1, b=2, c=3

>>> def printf(format,**keyword): 
  for k in keyword.keys(): 
    print "keyword[%s] %s %s"%(k,format,keyword[k]) 
 
     
>>> printf('is',one=1,tow=2,three=3) 
keyword[three] is 3
keyword[tow] is 2
keyword[one] is 1
Copy after login

These methods can be mixed together but the order must be paid attention to. The function will first accept fixed parameters, then optional parameters, then arbitrary parameters (tuple), then dictionary arbitrary parameters (dict)

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template