python中的函数

来源:互联网 发布:计算机加密软件 编辑:程序博客网 时间:2024/05/19 01:13
python doc上的内容

默认参数
def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):    while True:        ok = raw_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
使用的时候可以想下面那样使用:
  • giving only the mandatory argument: ask_ok('Doyoureally wanttoquit?')
  • giving one of the optional arguments: ask_ok('OKtooverwrite the file?', 2)
  • or even giving all arguments: ask_ok('OKtooverwrite the file?', 2, 'Come on, only yes or no!')
注意的是参数只被执行一次,当参数中有可变变量的时候需要注意,例如下面的例子
<pre><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">L</span><span class="o">=</span><span class="p">[]):</span>    <span class="n">L</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>    <span class="k">return</span> <span class="n">L</span><span class="k">print</span> <span class="n">f</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span><span class="k">print</span> <span class="n">f</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span><span class="k">print</span> <span class="n">f</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
输出将是下面的形式,这显然不是想要的结果。
[1][1, 2][1, 2, 3]


关键字参数
位置参数就如下面函数的vlotage参数,关键字参数就是kwarg=value这种形式,例如:
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):    print "-- This parrot wouldn't", action,    print "if you put", voltage, "volts through it."    print "-- Lovely plumage, the", type    print "-- It's", state, "!"
调用可以用下面的格式:
parrot(1000)                                          # 1 positional argumentparrot(voltage=1000)                                  # 1 keyword argumentparrot(voltage=1000000, action='VOOOOOM')             # 2 keyword argumentsparrot(action='VOOOOOM', voltage=1000000)             # 2 keyword argumentsparrot('a million', 'bereft of life', 'jump')         # 3 positional argumentsparrot('a thousand', state='pushing up the daisies')  # 1 positional, 1 keyword

但是下面的就是不合法的调用方式:
parrot()                     # required argument missingparrot(voltage=5.0, 'dead')  # non-keyword argument after a keyword argumentparrot(110, voltage=220)     # duplicate value for the same argumentparrot(actor='John Cleese')  # unknown keyword argument

需要注意的是,一个参数只能进行一次设置,关键字参数的设置左边的变量名必须是定义函数内的变量名,关键字参数的位置可以任意,但是位置参数的位置不能任意。

函数参数中的*name和**name这种格式的参数用法
*name必须出现在**name前面

*name将接收的参数放在tuple中
而**name将接受到的参数放在字典中
例子:
def cheeseshop(kind, *arguments, **keywords):    print "-- Do you have any", kind, "?"    print "-- I'm sorry, we're all out of", kind    for arg in <strong>arguments</strong>:        print arg    print "-" * 40    keys = sorted(<strong>keywords</strong>.keys())    for kw in keys:        print kw, ":", keywords[kw]
调用方式:
cheeseshop("Limburger", "It's very runny, sir.",           "It's really very, VERY runny, sir.",           shopkeeper='Michael Palin',           client="John Cleese",           sketch="Cheese Shop Sketch")
输出:
-- Do you have any Limburger ?-- I'm sorry, we're all out of LimburgerIt's very runny, sir.It's really very, VERY runny, sir.----------------------------------------client : John Cleeseshopkeeper : Michael Palinsketch : Cheese Shop Sketch



Arbitrary Argument Lists
Finally, the least frequently used option is to specify that a function can be called with an arbitrary number of arguments. These arguments will be wrapped up in a tuple (seeTuples and Sequences). Before the variable number of arguments, zero or more normal arguments may occur.
def write_multiple_items(file, separator, *args):    file.write(separator.join(args))

Unpacking Argument Lists
>>> range(3, 6)             # normal call with separate arguments[3, 4, 5]>>> args = [3, 6]>>> range(*args)            # call with arguments unpacked from a list[3, 4, 5]

>>> def parrot(voltage, state='a stiff', action='voom'): ...     print "-- This parrot wouldn't", action,...     print "if you put", voltage, "volts through it.",...     print "E's", state, "!"...>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"} #from a dic>>> parrot(**d)-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !



Lambda Expressions
lambdaa,b: a+b : this return the sum of a and b
例子:
>>> def make_incrementor(n):...     return lambda x: x + n...>>> f = make_incrementor(42)>>> f(0)42>>> f(1)43

另外lamda表达式可以作为函数实参使用
>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]>>> pairs.sort(key=lambda pair: pair[1])>>> pairs[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]








0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 身上皮肤很黑怎么办?好想穿短裙 家里有很多小飞虫怎么办 家里有垃圾中飞出虫子怎么办 雷蛇笔记本很烫怎么办 登录监控器的账号锁了怎么办 悦借钱登录账号被锁怎么办 365账号登录被锁怎么办 台式电脑cpu温度过高怎么办 UG2.0打不开错误—15怎么办 键盘空格键删除键失灵怎么办 耳麦检测声音不分左右怎么办 吃生萝卜胃疼怎么办 幼兔拉稀怎么办没精神 自酿米酒酸了怎么办 用冰敷脸感觉红烫了怎么办 吃了海兔的内脏怎么办 吃了鱿鱼的吸盘怎么办 想开个烧烤店没学过怎么办 墨鱼汁弄衣服上怎么办 干鱿鱼泡开发黄怎么办 吃了芥末胃疼怎么办 手撕鱿鱼咸了怎么办 孕妇吃了点芥末怎么办 葡萄酒上面有一层白霉怎么办 手机一不小心把视频删了怎么办 柑橘7月份果实小怎么办 鹦鹉鱼身上有小白点怎么办 鹦鹉鱼身上烂了怎么办 红鹦鹉鱼变黑了怎么办 唱美声总夹嗓子怎么办 发财树树干出褶怎么办 月季花夏天换盆出现黄叶怎么办 刚种的月季枯了怎么办 新买的月季黄叶了怎么办 月季花叶孑轰发黄怎么办? 新种的月季苗弱怎么办? 月季换盆后浇透水叶子黄了怎么办 肉肉移栽后浇透水怎么办 月季花扦插的没长根发芽了怎么办 君子兰发的小苗怎么办 蔷薇光长枝条不开花怎么办