定义函数
def fib(n):
'''do nothing'''
pass
- 关键字
def
定义函数,其后跟有函数名和以括号扩起来的形参列表。组成的函数体从下一行开始,且必须缩进。 - 函数体第一行是可选的字符串,作用相当于Java
/** */
注释里的内容。 - 同JavaScript类似,执行一个函数会引入一个用于存储局部变量的新符号表;变量引用首先查找局部符号表,然后是上层函数的局部符号表,然后是全局符号表,最后是内置名称表。
- 在函数体内部无法给一个全局变量赋值,虽然可以引用它们。
- Python的参数传递机制是值传递,同Java类似。
- Python中的函数名可以赋值给其他变量,然后使用括号调用函数,这点同JavaScript类似。
- 即使没有
return
语句的函数也会返回一个值None
。
默认值函数
def ask_ok(prompt, retries=4, complaint='Yes or no'):
while True:
ok = raw_input(prompt)
print complaint
默认值在函数定义的时候计算,并且只计算一次,例如
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) # [1]
print f(2) # [1, 2]
print f(3) # [1, 2, 3]
解决方法如下
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
关键字函数
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 argument
parrot(voltage=1000) # 1 keyword argument
parrot(voltage=1000000, action='VOOOOOM') # 2 keyword arguments
parrot(action='VOOOOOM', voltage=1000000) # 2 keyword arguments
parrot('a million', 'bereft of life', 'jump') # 3 positional arguments
parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword
任意参数列表
def write_multiple_items(file, separator, *args):
file.write(separator.join(args))
**name
形式的参数接受一个字典,而且必须位于*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 arguments:
print arg
print "-" * 40
keys = sorted(keywords.keys())
for kw in keys:
print kw, ":", keywords[kw]
参数列表的拆分
range(3, 6) # normal call with separate arguments
# output [3, 4, 5]
args = [3, 6]
range(*args) # call with arguments unpacked from a list
# output [3, 4, 5]
lambda 表达式
lambda局限于只能有一个单独的表达式。他们只是普通函数定义的语法糖。
>>> def make_incrementor(n):
... return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43