函数是一个对象
def fun(n):
'''注释'''
return 1 if n < 2 else n * fun(n-1)
print(fun(42))
print(fun.__doc__)
print(type(fun))
输出如下:
1405006117752879898543142606244511569936384000000000
注释
<class 'function'>
高阶函数
一个函数可以传送一个函数作为参数,或者一个函数可以返回一个函数对象,这种特性就叫做高阶函数。比如map函数:
print(list(map(fun, range(5))))
输出:[1, 1, 2, 6, 24]
这里fun函数对象作为一个参数传送给map函数。
尽可能使用列表解析和生成表达式取代map和fiter/reduce。
lambda表达式表示匿名函数。
用函数callable()来区分是否可调用对象。
创建自定义调用对象:
class callfun:
def __init__(self, a):
self._a = list(a)
def pick(self):
print(self._a)
def __call__(self):
self.pick()
t = callfun('abcd')
t.pick()
t()
输出如下:
['a', 'b', 'c', 'd']
['a', 'b', 'c', 'd']
partial类绑定操作
from operator import mul
from functools import partial
t = partial(mul, 3)
print(list(map(t, range(1,20))))
输出如下:
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57]