在Python中,可以定义包含若干参数的函数,这里有几种可用的形式,也可以混合使用:

1. 默认参数

最常用的一种形式是为一个或多个参数指定默认值。

>>> def ask_ok(prompt,retries=4,complaint='Yes or no Please!'):
while True:
ok=input(prompt)
if ok in ('y','ye','yes'):
return True
if ok in ('n','no','nop','nope'):
return False
retries=retries-1
if retries<0:
raise IOError('refusenik user')
print(complaint)

这个函数可以通过几种方式调用:

  • 只提供强制参数
>>> ask_ok('Do you really want to quit?')
Do you really want to quit?yes
True
  • 提供一个可选参数
>>> ask_ok('OK to overwrite the file',2)
OK to overwrite the fileNo
Yes or no Please!
OK to overwrite the fileno
False
  • 提供所有的参数
>>> ask_ok('OK to overwrite the file?',2,'Come on, only yes or no!')
OK to overwrite the file? test
Come on, only yes or no!
OK to overwrite the file?yes
True

2. 关键字参数

函数同样可以使用keyword=value形式通过关键字参数调用

>>> def parrot(voltage,state='a stiff',action='voom',type='Norwegian Blue'):
print("--This parrot wouldn't", action, end=' ')
print("if you put",voltage,"volts through it.")
print("--Lovely plumage, the",type)
print("--It's",state,"!") >>> parrot(1000)
--This parrot wouldn't voom if you put 1000 volts through it.
--Lovely plumage, the Norwegian Blue
--It's a stiff !
>>> parrot(action="vooooom",voltage=1000000)
--This parrot wouldn't vooooom if you put 1000000 volts through it.
--Lovely plumage, the Norwegian Blue
--It's a stiff !
>>> parrot('a thousand',state='pushing up the daisies')
--This parrot wouldn't voom if you put a thousand volts through it.
--Lovely plumage, the Norwegian Blue
--It's pushing up the daisies !

但是以下的调用方式是错误的:

>>> parrot(voltage=5, 'dead')
SyntaxError: non-keyword arg after keyword arg
>>> parrot()
Traceback (most recent call last):
File "<pyshell#57>", line 1, in <module>
parrot()
TypeError: parrot() missing 1 required positional argument: 'voltage'
>>> parrot(110, voltage=220)
Traceback (most recent call last):
File "<pyshell#58>", line 1, in <module>
parrot(110, voltage=220)
TypeError: parrot() got multiple values for argument 'voltage'
>>> parrot(actor='John')
Traceback (most recent call last):
File "<pyshell#59>", line 1, in <module>
parrot(actor='John')
TypeError: parrot() got an unexpected keyword argument 'actor'
>>> parrot(voltage=100,action='voom',action='voooooom')
SyntaxError: keyword argument repeated

Python的函数定义中有两种特殊的情况,即出现*,**的形式。

*用来传递任意个无名字参数,这些参数会以一个元组的形式访问

**用来传递任意个有名字的参数,这些参数用字典来访问

(*name必须出现在**name之前)

>>> def cheeseshop1(kind,*arguments,**keywords):
print("--Do you have any",kind,"?")
print("--I'm sorry, we're all out of",kind)
for arg in arguments:
print(arg)
print("-"*40)
keys=sorted(keywords.keys())
for kw in keys:
print(kw,":",keywords[kw]) >>> cheeseshop1("Limbuger","It's very runny, sir.","It's really very, very runny, sir.",shopkeeper="Michael Palin",client="John",sketch="Cheese Shop Sketch")
--Do you have any Limbuger ?
--I'm sorry, we're all out of Limbuger
It's very runny, sir.
It's really very, very runny, sir.
----------------------------------------
client : John
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch
>>>

3. 可变参数列表

最常用的选择是指明一个函数可以使用任意数目的参数调用。这些参数被包装进一个元组,在可变数目的参数前,可以有零个或多个普通的参数

通常,这些可变的参数在形参列表的最后定义,因为他们会收集传递给函数的所有剩下的输入参数。任何出现在*args参数之后的形参只能是“关键字参数”

>>> def contact(*args,sep='/'):
return sep.join(args) >>> contact("earth","mars","venus")
'earth/mars/venus'

4. 拆分参数列表

当参数是一个列表或元组,但函数需要分开的位置参数时,就需要拆分参数

  • 调用函数时使用*操作符将参数从列表或元组中拆分出来
>>> list(range(3,6))
[3, 4, 5]
>>> args=[3,6]
>>> list(range(*args))
[3, 4, 5]
>>>
  • 以此类推,字典可以使用**操作符拆分成关键字参数
>>> def parrot(voltage,state='a stiff',action='voom'):
print("--This parrot wouldn't", action,end=' ')
print("if you put",voltage,"volts through it.",end=' ')
print("E's", state,"!") >>> d={"voltage":"four million","state":"bleedin' demised","action":"VOOM"}
>>> parrot(**d)
--This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !

5. Lambda

在Python中使用lambda来创建匿名函数,而用def创建的是有名称的。

  • python lambda会创建一个函数对象,但不会把这个函数对象赋给一个标识符,而def则会把函数对象赋值给一个变量
  • python lambda它只是一个表达式,而def则是一个语句
>>> def make_incrementor(n):
return lambda x:x+n >>> f=make_incrementor(42)
>>> f(0)
42
>>> f(2)
44
>>> g=lambda x:x*2
>>> print(g(3))
6
>>> m=lambda x,y,z:(x-y)*z
>>> print(m(3,1,2))
4

6. 文档字符串

关于文档字符串内容和格式的约定:

  • 第一行应该总是关于对象用途的摘要,以大写字母开头,并且以句号结束
  • 如果文档字符串包含多行,第二行应该是空行
>>> def my_function():
"""Do nothing, but document it. No, really, it doesn't do anything.
"""
pass >>> print(my_function.__doc__)
Do nothing, but document it. No, really, it doesn't do anything. >>>

Python学习 Part2:深入Python函数定义的更多相关文章

  1. Python学习札记(十一) Function2 函数定义

    参考:定义函数 Note: 先看一段代码实例(Barefoot topo.py): def read_topo(): nb_hosts = 0 nb_switches = 0 links = [] w ...

  2. python学习第五讲,python基础语法之函数语法,与Import导入模块.

    目录 python学习第五讲,python基础语法之函数语法,与Import导入模块. 一丶函数简介 1.函数语法定义 2.函数的调用 3.函数的文档注释 4.函数的参数 5.函数的形参跟实参 6.函 ...

  3. Python学习教程(Python学习视频_Python学些路线):Day06 函数和模块的使用

    Python学习教程(Python学习视频_Python学些路线):函数和模块的使用 在讲解本章节的内容之前,我们先来研究一道数学题,请说出下面的方程有多少组正整数解. $$x_1 + x_2 + x ...

  4. Python学习笔记之常用函数及说明

    Python学习笔记之常用函数及说明 俗话说"好记性不如烂笔头",老祖宗们几千年总结出来的东西还是有些道理的,所以,常用的东西也要记下来,不记不知道,一记吓一跳,乖乖,函数咋这么多 ...

  5. python学习第九讲,python中的数据类型,字符串的使用与介绍

    目录 python学习第九讲,python中的数据类型,字符串的使用与介绍 一丶字符串 1.字符串的定义 2.字符串的常见操作 3.字符串操作 len count index操作 4.判断空白字符,判 ...

  6. python学习第三讲,python基础语法之注释,算数运算符,变量.

    目录 python学习第三讲,python基础语法之注释,算数运算符,变量. 一丶python中的基础语法,注释,算数运算符,变量 1.python中的注释 2.python中的运算符. 3.pyth ...

  7. python入门灵魂5问--python学习路线,python教程,python学哪些,python怎么学,python学到什么程度

    一.python入门简介 对于刚接触python编程或者想学习python自动化的人来说,基本都会有以下python入门灵魂5问--python学习路线,python教程,python学哪些,pyth ...

  8. python学习第一讲,python简介

    目录 python学习第一讲,python简介 一丶python简介 1.解释型语言与编译型语言 2.python的特点 3.python的优缺点 二丶第一个python程序 1.python源程序概 ...

  9. Python学习笔记(四)Python函数的参数

    Python的函数除了正常使用的必选参数外,还可以使用默认参数.可变参数和关键字参数. 默认参数 基本使用 默认参数就是可以给特定的参数设置一个默认值,调用函数时,有默认值得参数可以不进行赋值,如: ...

随机推荐

  1. mac10.10 打造Python多版本虚拟环境

    一.简介 1.在操作系统mac10.10(yosemite)中搭建Python多版本虚拟环境: 2.多版本虚拟环境包含三个含义: 在一个操作系统中安装多个版本的Python,不同版本可以随意切换,例如 ...

  2. 对于iPhone描述文件的签名认证

    1.购买SSL证书验证(跟https认证一样) 2.iphone 签名.mobileconfig文件 company.mobileconfig 未签名的mobileconfig文件 server.cr ...

  3. Linux系统上安装字体

    最近项目中需要控制字体类型,然后就上网查了一下在linux系统上安装字体,在window上和linux上,字体要求一样,都是ttf格式,下面这是window上的字体截图 在linux系统中的/usr/ ...

  4. 将自定义参数从uboot传入kernel的并读取的方法【转】

    本文转载自:http://blog.csdn.net/qq_29729577/article/details/50580727 希望朋友们多多指点,好的技术或心得一起分享: uboot向kernel传 ...

  5. led子系统【转】

    本文转载自:http://blog.csdn.net/yuanlulu/article/details/6438841 版权声明:本文为博主原创文章,未经博主允许不得转载. ============= ...

  6. jquery特效(3)—轮播图①(手动点击轮播)

    写了一个轮播图练练手,先写了一个手动点击轮播的轮播图,随后我会慢慢接着深入写自动轮播图和鼠标悬浮图片停止移动轮播图等,虽然今天我生日,但是代码还是得写的,不能找借口放松自己,原地踏步也算后退. 下面来 ...

  7. IOS开发学习笔记(1)-----UILabel 详解

    1. [代码][C/C++]代码     //创建uilabelUILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(20, 40, ...

  8. BZOJ 1624 [Usaco2008 Open] Clear And Present Danger 寻宝之路:floyd

    题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=1624 题意: 农夫约翰正驾驶一条小艇在牛勒比海上航行. 海上有N(1≤N≤100)个岛屿, ...

  9. Dom4J 解析xml ,类查询

    /** * 从XML文件比对,传入provinceId 返回 provinceShortName * @param provinceid * @return */ public static Stri ...

  10. jquery的跨域请求

    项目中关于ajax jsonp的使用,出现了问题:可以成功获得请求结果,但没有执行success方法总算搞定了,记录一下 function TestAjax() {    $.ajax({       ...