1、创建自己的函数
l Callable()函数:检查是否可以调用
>>> from math import sqrt as x
>>> y = 1
>>> callable(x)
True
>>> callable(y)
False
l 创建函数:用def关键字定义,用return语句返回结果
def fibs(num):
result = [0, 1]
for i in range(num-2):
result.append(result[-2] + result[-1])
return result
(1) 函数Doc
l 函数开始处的一个String(称为docstring)
>>> def square(x):
... 'Calculates the square of the number x.'
... return x*x
l 使用help()函数显示函数Doc
>>> help(square)
Help on function square in module __main__:
square(x)
Calculates the square of the number x.
(2) keyword参数和缺省值
l 函数的参数在调用时是有顺序的,但使用keyword参数不用关心顺序问题:
>>> def hello_1(greeting, name): print '%s, %s!' % (greeting, name)
>>> hello_1(name='world', greeting='Hello')
Hello, world!
l 在创建函数时可以为参数指定缺省值:
def hello_3(greeting='Hello', name='world'): print '%s, %s!' % (greeting, name)
l 下面各种调用的情况:
>>> hello_3()
Hello, world!
>>> hello_3('Greetings')
Greetings, world!
>>> hello_3('Greetings', 'universe')
Greetings, universe!
l 如果只使用greeting的缺省值,可以使用keyword参数:
>>> hello_3(name='Gumby')
Hello, Gumby!
l 可以混合使用必选参数和带缺省值的参数,但前者必须放在最前面:
>>> def hello_4(name, greeting='Hello', punctuation='!'):
... print '%s, %s%s' % (greeting, name, punctuation)
(3) 集合参数
l 在参数前面加“*”,表示调用时其后的值放到Tuple中
>>> def print_params_2(title, *params):
... print title,
... print params
>>> print_params_2('Params:', 1, 2, 3)
Params: (1, 2, 3)
l Tuple集合参数不能使用keyword参数:
>>> print_params_2('Hmm...', something=42)
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
TypeError: print_params_2() got an unexpected keyword argument 'something'
l 可以使用Dictionary集合参数(在参数前面加“**”)
>>> def print_params_3(title, **params):
... print title,
... print params
>>> print_params_3('Hmm...', something=42)
Hmm... {'something': 42}
l “*”、“**”的逆向使用:
>>> params = ('Sir Robin', 'Well met')
>>> hello_3(*params)
Sir Robin, Well met!
>>> params = {'name': 'Sir Robin', 'greeting': 'Well met'}
>>> hello_3(**params)
Well met, Sir Robin!
2、范围(或者namespace)
l 除了全局范围之外,每个函数的调用都会创建一个范围,vars()函数返回当前范围中所有的变量及其值的Dictionary:
>>> def foo():
... x = 42
... print vars()
...
>>> x = 1
>>> foo()
{'x': 42}
>>> vars()
{'__builtins__': <module '__builtin__' (built-in)>, 'pywin': <module 'pywin' from 'D:/workshop/Python24/Lib/site-packages/pythonwin/pywin/__init__.pyc'>, 'x': 1, '__name__': '__main__', 'foo': <function foo at 0x00FF5BB0>, '__doc__': None}
l 当函数中的变量和全局变量同名时,可以使用globals()函数(返回Dictionary)来访问全局变量:
>>> def combine(parameter):
print parameter + globals()['parameter']
...
>>> parameter = 'berry'
>>> combine('Shrub')
Shrubberry
3、有用的函数
(1) map
l LAMBDA表达式:以关键字lambda开始,后面跟参数,然后是“:”,最后是表达式
lambda x, y, z: x + y + z
l map():通过指定函数应用到每个元素,将一个Sequence映射成另一个Sequence
>>> numbers = [72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33]
>>> map(lambda n: 2*n, numbers)
[144, 202, 216, 216, 222, 88, 64, 238, 222, 228, 216, 200, 66]
l 由于String是字符Sequence,可以直接使用,但要注意返回的是List
>>> map(ord, 'Hello, world!')
[72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33]
(2) filter
l filter():通过指定函数应用到每个元素,将一个Sequence符合的元素组成另一个Sequence
>>> numbers = [72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33]
>>> filter(lambda n: n % 2 == 0, numbers)
[72, 108, 108, 44, 32, 114, 108, 100]
l 使用List包含可以实现map()和flter()的相同功能:
>>> [chr(n) for n in numbers] # characters corresponding to numbers
['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!']
>>> [n for n in numbers if n % 2 == 0] # filters out the odd numbers
[72, 108, 108, 44, 32, 114, 108, 100]
(3) reduce
l reduce():使用Sequence中开始的两个元素调用指定的函数,然后用结果和第3个元素调用指定的函数,依次类推到最后的元素,最后返回结果值
l 典型的例子是求和:
>>> numbers = [72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33]
>>> reduce(lambda x, y: x+y, numbers)
1161