python 中的函式定义
python 中的函式定义

python 中的函式定义
• 发表于 7个月前
• 阅读 14
• 收藏 0
• 评论 0

``````>>> def fib(n):    # 打印 Fibonacci 序列到 n
...     """打印到 n 的 Fibonacci 序列."""
...     a, b = 0, 1
...     while a < n:
...         print(a, end=' ')
...         a, b = b, a+b
...     print()
...
>>> # 现在调用我们刚定义的函式:
... fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597``````

``````>>> fib(0)
>>> print(fib(0))
None``````

* 关于符号表

``````import dis

c = 3

def abc():
a = 1
b = a + c

dis.dis(abc)``````

`````` 19           0 LOAD_CONST               1 (1)
3 STORE_FAST               0 (a)

20           6 LOAD_FAST                0 (a)
9 LOAD_GLOBAL              0 (c)
13 STORE_FAST               1 (b)
16 LOAD_CONST               0 (None)
19 RETURN_VALUE``````

### 默认参数

``````def meet(you='lisi', him='wangwu'):
print(you,'meet',him)

meet()
meet('wo')
meet('wo','zhangsan')
``````

``````i = 5

def f(arg=i):
print(arg)

i = 6
f()

# output:
5``````

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

print(f(1))
print(f(2))
print(f(3))

# output:
[1]
[1, 2]
[1, 2, 3]``````

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

* 为什么默认参数会变？

``````def foo(bar=None):
bar = bar or []``````

``````def foo(bar=[]):
bar = list(bar)``````

### 关键字参数

``````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)
parrot(action = 'VOOOOOM', voltage = 1000000)
parrot('a thousand', state = 'pushing up the daisies')
parrot('a million', 'bereft of life', 'jump')``````

``````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)
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")``````

``````-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch``````

### 任意参数列表

``````def write_multiple_items(file, separator, *args):
file.write(separator.join(args))``````

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

### 参数列表解包

``````def cute(sex, age, height):
print(sex,age,height,end=' ')
print()

t = ['female', 18, 167]
cute(*t)

# output:
female 18 167 ``````

``````d = {'sex': 'male', 'age':18, 'height': 172}
cute(**d)

# output:
male 18 172 ``````

* 或 **操作符有两个作用：

*arg 表示分散的参数，接受分散的参数。解析后的 arg 表示tuple或者map，可以传入函数参数为元组的函数。