Python(2)深入Python函数定义
在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(2)深入Python函数定义的更多相关文章
- Python之路 day3 函数定义 *args及**kwargs
#!/usr/bin/env python # -*- coding:utf-8 -*- #Author:ersa import time # def logger(): # time_format ...
- python基础语法5 函数定义,可变长参数
函数 1.什么是函数 函数就是一种工具. 可以重复调用 2.为什么要用函数 1.防止代码冗(rong)余 2.代码的可读性差 3.怎么用函数 1.定义函数-->制造工具 2.调用函数--> ...
- [Python]Python Class 中的 函数定义中的 self
In [80]: class MyClass001: ....: def selfDemo(self): ....: print 'My Demo' ....: In [81]: p = MyClas ...
- 【循序渐进学Python】6.Python中的函数
1. 创建函数 一个函数代表一个行为并且返回一个结果(包括None),在Python中使用def关键字来定义一个函数,如下: def hello(name): print 'hello,' + nam ...
- 【Python基础学习二】定义变量、判断、循环、函数基本语法
先来一个愉快的Hello World吧,就是这么简单,不需要写标点符号,但是需要严格按照缩进关系,Python变量的作用域是靠tab来控制的. print("Hello World" ...
- Python 2.7 学习笔记 基本语法和函数定义
本文介绍下python的基本语法 一.变量定义 不需要说明类型,也不需要像js等脚本语言使用var等标识符.直接声明即可,如: num=1 说明:上面语句声明了一个变量num,并在声明时初始化值为 1 ...
- python函数定义
刚学用Python的时候,特别是看一些库的源码时,经常会看到func(*args, **kwargs)这样的函数定义,这个*和**让人有点费解.其实只要把函数参数定义搞清楚了,就不难理解了. 先说说函 ...
- python入门(14)定义函数和接收返回值
定义函数: 定义一个求绝对值的my_abs函数为例: def my_abs(x): if x >= 0: return x else: return -x 如果没有return语句,函数执行完毕 ...
- python中的函数(定义、多个返回值、默认参数、参数组)
函数定义 在python中函数的定义以及调用如下代码所示: def test(x): y = x+1 return y result = test(2) print(result) 多个返回值的情况 ...
随机推荐
- (NO.00001)iOS游戏SpeedBoy Lite成形记(十三)
游戏特效部分就先这样了,因为毕竟是Lite版本,而且是第一个App,所以咱们把主要精力放在游戏可玩逻辑上吧(虽然已经厚颜无耻的加了不少特效了). 说句题外话:游戏美工是独立开发者不可逾越的鸿沟,是无法 ...
- 【一天一道LeetCode】#58. Length of Last Word
一天一道LeetCode系列 (一)题目 Given a string s consists of upper/lower-case alphabets and empty space charact ...
- 常用Map实现类对比
翻译人员: 铁锚 翻译时间: 2013年12月12日 原文链接: HashMap vs. TreeMap vs. Hashtable vs. LinkedHashMap Map 是最常用的数据结构之一 ...
- 【Qt编程】设计ColorBar颜色栏
画过图的都知道,我们常常用颜色的深浅来表示值的大小,在Matlab作图中,我们使用的是colorbar这个函数来给出颜色的直观参考.下面给出Matlab的示例:在Matlab命令窗口输入: figur ...
- 【Android 应用开发】Android中使用ViewPager制作广告栏效果 - 解决ViewPager占满全屏页面适配问题
. 参考界面 : 携程app首页的广告栏, 使用ViewPager实现 自制页面效果图 : 源码下载地址: http://download.csdn.net/detail/han1202 ...
- 【面试笔试算法】Problem 1 : DP滑雪问题--网易互联网算法实习生2017笔试题
Description Michael喜欢滑雪百这并不奇怪,因为滑雪的确很刺激.可是 为了获得速度,滑的区域必须向下倾斜,而且当你滑到坡底,你不得不再次走上坡或者等待升降机来载你.Michael想知道 ...
- C++模板总结
在编写含有模板的程序的时候,我还是按照一个头文件声明,一个源文件的方法来组织,结果编译的时候总出现一些很奇怪的语法问题,但程序明明是没有问题的.后来经过查阅才知道原来是因为C++编译器不支持对模板的分 ...
- Mybatis批量插入、批量更新
合理的使用批量插入.更新对优化有很大的作用,速度明显快了N倍. 数据库连接串后面要新增:&allowMultiQueries=true 批量插入的最大限制主要是看你整条sql占用的大小,所以可 ...
- DH密钥交换非对称加密
迪菲-赫尔曼密钥交换(Diffie–Hellman key exchange,简称"D–H") 是一种安全协议. 它可以让双方在完全没有对方任何预先信息的条件下通过不安全信道建立起 ...
- 不要在#include中使用".."
按照Google C++风格,不应该在#include中使用点号和双点号. 例如:project/scr/base/logging.h 应该这样包含: #include "base/logg ...