Skip to content Skip to main navigation Skip to footer

# Python: 深入Python函数定义

Table of Contents

## 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)
&#91;/code&#93;
<p>这个函数可以通过几种不同的方式调用：</p>
<ul>
<li>

<li>

<li>

</ul>
<p>

<p>默认值在函数定义作用被解析，如下所示：</p>
<pre><code>i = 5
def f(arg = i):
print(arg)
i = 6
f()</code></pre>
<p>

<p>

def f(a, L = []):
L.append(a)
return L
print(f(1))
print(f(2))
print(f(3)) ```

``````[1]
[1, 2]
[1, 2, 3]``````

```def f(a, L=None):
if L is None:
L = []
L.append(a)
return L ```

## 2. 关键字参数

`def parrot(voltage, state = 'a stiff', action = 'voom', type = 'Norwegian Blue'): `

```parrot(1000)
parrot(voltage = 1000)
parrot(voltage = 10000, action = 'VOOOM')
parrot(action = 'VOOOOM', voltage = 1000) # action 写在前面也是OK的！
parrot('a million', 'bereft of life', 'jump') # voltage = 'a milion'
parrot('a thousand', state = 'pushing up the daisies') # voltage = 'a thousand' ```

```parrot() # voltage必须有值
parrot(voltage = 5.0, 'dead') # 一旦有一个参数是通过关键字指定的，后面的也必须都是
parrot(110, voltage = 220) # 两个voltage的值
parrot(acotr = 'Jonh Cleese') # 没有voltage的值 ```

```def cheeseshop(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) # 打印40个’-‘
keys = sorted(keywords.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>") ```

## 3. 可变参数列表

```def write_multiple_items(file, separator, *args):
file.write(separator.join(args)) # 用separator符号将arg里的内容连在一起 ```

```>>> def concat(*args, sep="/>"):
...    return sep.join(args)
...
>>> concat("earth>", "mars>", "venus>")
'earth/mars/venus'
>>> concat("earth>", "mars>", "venus>", sep=".>")
'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形式

```>>> def make_incrementor(n):
...     return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43 ```
###### 0 Comments

There are no comments yet