浅谈Python中函数的参数传递

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

1.普通的参数传递

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

2.参数个数可选,参数有默认值的传递

>>> 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

参数sep的缺省值是'_' 如果这个参数不给定值就会使用缺省值 如果给定 则使用给定的值

需要注意 如果一个参数是可选参数 那么它后面所有的参数都应该是可选的,另外 可选参数的顺序颠倒依然可以正确的给对应的参数赋值 但必须清楚的指明变量名和值

3.个数可变参数

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

函数中的*arg必须是最后一个参数,*表示任意多个参数,*arg会把除了前面以外所有的参数放到一个tuple里面传递给函数,可以在函数中通过arg来访问

arg是一个tuple,可以通过访问tuple的方法在函数中访问arg

另一种方式传递任意个数参数是通过dictionary的方式来传递 同样也可以接受多个参数 但是每个参数需要指明名称对应关系比如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

这些方法可以混在一起用 但是一定要注意顺序,函数会先接受固定参数,然后可选参数,然后任意参数(tuple),然后字典任意参数(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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!