函数式编程(请注意多了一个“式”字)——Functional Programming,虽然也可以归结到面向过程的程序设计,但其思想更接近数学计算。
函数式编程就是一种抽象程度很高的编程范式,纯粹的函数式编程语言编写的函数没有变量,因此,任意一个函数,只要输入是确定的,输出就是确定的,这种纯函数我们称之为没有副作用。而允许使用变量的程序设计语言,由于函数内部的变量状态不确定,同样的输入,可能得到不同的输出,因此,这种函数是有副作用的。
函数式编程的一个特点就是,允许把函数本身作为参数传入另一个函数,还允许返回一个函数!由于Python允许使用变量,因此,Python不是纯函数式编程语言。
高阶函数
高阶函数英文叫Higher-order function。把函数作为参数传入,这样的函数称为高阶函数,函数式编程就是指这种高度抽象的编程范式。
1、一步步理解高阶函数
变量可以指向函数
以Python内置的求绝对值的函数abs()
为例,调用该函数用以下代码:
>>> abs(-10)
10
abs(-10)
是函数调用,而abs
是函数本身。
>>> abs
<built-in function abs>
函数本身也可以赋值给变量,即:变量可以指向函数。
>>> f = abs
>>> f
<built-in function abs>
>>> f(-10)
10
说明变量f
现在已经指向了abs
函数本身。直接调用abs()
函数和调用变量f()
完全相同。
函数名也是变量
函数名其实就是指向函数的变量!对于abs()
这个函数,完全可以把函数名abs
看成变量,它指向一个可以计算绝对值的函数!
>>> abs = 10
>>> abs(-10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
把abs
指向10
后,就无法通过abs(-10)
调用该函数了!因为abs
这个变量已经不指向求绝对值函数而是指向一个整数10
!
注意! 由于abs
函数实际上是定义在import builtins
模块中的,所以,要让修改abs
变量的指向在其它模块也生效,要用import builtins; builtins.abs = 10
。
传入函数
既然变量可以指向函数,函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。
一个最简单的高阶函数:
def add(x, y, f):
return f(x) + f(y)
推导计算过程为:
x = -5
y = 6
f = abs
f(x) + f(y) ==> abs(-5) + abs(6) ==> 11
return 11
2、map/reduce
经典论文MapReduce: Simplified Data Processing on Large Clusters中有对map/reduce概念的详细解析。
map()
函数接收两个参数,一个是函数,一个是可迭代对象Iterable
,map
将传入的函数依次作用到序列的每个元素,并把结果作为新的迭代器Iterator
返回。
举例说明,比如我们有一个函数f(x)=x*x
,要把这个函数作用在一个list [1, 2, 3, 4, 5, 6, 7, 8, 9]
上,就可以用map()
实现如下:
用Python代码实现:
>>> def f(x):
... return x * x
...
>>> r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> r
<map object at 0x00000206DDCFBF70>
>>> list(r)
[1, 4, 9, 16, 25, 36, 49, 64, 81]
map()
传入的第一个参数是f
,即函数对象本身。由于结果r
是一个Iterator
,Iterator
是惰性序列,因此通过list()
函数让它把整个序列都计算出来并返回一个list
。
map()
作为高阶函数,事实上它把运算规则抽象了,因此,我们不但可以计算简单的f(x)=x*x
,还可以计算任意复杂的函数,比如,把这个list所有数字转为字符串:
>>> list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
['1', '2', '3', '4', '5', '6', '7', '8', '9']
reduce
把一个函数作用在一个序列[x1, x2, x3, ...]
上,这个函数必须接收两个参数,reduce
把结果继续和序列的下一个元素做累积计算,其效果就是:
reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
比如,把序列[1, 3, 5, 7, 9]
变换成整数13579
:
>>> from functools import reduce
>>> def fn(x, y):
... return x * 10 + y
...
>>> reduce(fn, [1, 3, 5, 7, 9])
13579
把str
转换为int
的函数:
>>> from functools import reduce
>>> def fn(x, y):
... return x * 10 + y
...
>>> def char2num(s):
... digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
... return digits[s]
...
>>> reduce(fn, map(char2num, '13579')) # 对于元素‘1’,map()使得char2num函数作用在上面,返回的就是数字1;然后元素‘3’,返回数字3;...最终生成列表[1,3,5,7,9];接着reduce()使得fn函数作用于这个列表,先1*10+3=13,然后13*10+5=135,然后135*10+7=1357,最后1357*10+9=13579
13579
# 对于元素‘1’,map()使得char2num函数作用在上面,返回的就是数字1;然后元素‘3’,返回数字3;...最终生成列表[1,3,5,7,9];
# 接着reduce()使得fn函数作用于这个列表,先1*10+3=13,然后13*10+5=135,然后135*10+7=1357,最后1357*10+9=13579
整理成一个str2int
的函数就是:
from functools import reduce
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
def str2int(s):
def fn(x, y):
return x * 10 + y
def char2num(s):
return DIGITS[s]
return reduce(fn, map(char2num, s))
还可以用lambda
函数进一步简化成:
from functools import reduce
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
def char2num(s):
return DIGITS[s]
def str2int(s):
return reduce(lambda x, y: x * 10 + y, map(char2num, s))
练习
1、利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入:[‘adam’, ‘LISA’, ‘barT’],输出:[‘Adam’, ‘Lisa’, ‘Bart’]:
函数实现:
# -*- coding: utf-8 -*-
def normalize(name):
return name.capitalize()
测试:
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)
测试结果:
['Adam', 'Lisa', 'Bart']
2、请编写一个prod()函数,可以接受一个list并利用reduce()求积:
函数实现:
# -*- coding: utf-8 -*-
from functools import reduce
def prod(L):
def f(x, y):
return x * y
return reduce(f, L)
测试:
print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
if prod([3, 5, 7, 9]) == 945:
print('测试成功!')
else:
print('测试失败!')
测试结果:
3 * 5 * 7 * 9 = 945
测试成功!
3、利用map和reduce编写一个str2float函数,把字符串’123.456’转换成浮点数123.456:
函数实现:
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
from functools import reduce
def str2float(s):
def fn(x, y):
return x * 10 + y
def char2num(s):
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '.':-1}
return DIGITS[s]
L = list(map(char2num, s))
k = L.index(-1)
return reduce(fn, L[:k] + L[k+1:]) / 10**len(L[k+1:])
# L1 = L[:k] + L[k+1:]
# temp = reduce(fn, L1)
# # n = len(L[k+1:])
# # k = 1
# # while(n > 0):
# # k *= 10
# # n -= 1
# return temp/10**n
测试:
print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
print('测试成功!')
else:
print('测试失败!')
测试结果:
PS D:\MyCode\PythonCode\Test> & D:/Tool/Python/Python311/python.exe d:/MyCode/PythonCode/Test/hello.py
str2float('123.456') = 123.456
测试成功!
3、filter
Python内建的filter()
函数用于过滤序列。
和map()
类似,filter()
也接收一个函数和一个序列。和map()
不同的是,filter()
把传入的函数依次作用于每个元素,然后根据返回值是True
还是False
决定保留还是丢弃该元素。
filter()
的作用是从一个序列中筛出符合条件的元素。由于filter()
使用了惰性计算,返回的是一个迭代器Iterator
,所以只有在取filter()
结果的时候,才会真正筛选并每次返回下一个筛出的元素。
把一个序列中的空字符串删掉,可以这么写:
def not_empty(s):
return s and s.strip()
list(filter(not_empty, ['A', '', 'B', None, 'C', ' ']))
# 结果: ['A', 'B', 'C']
用filter求素数
埃氏筛法:
首先,列出从2
开始的所有自然数,构造一个序列:
2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, …
取序列的第一个数2
,它一定是素数,然后用2
把序列的2
的倍数筛掉:
3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, …
取新序列的第一个数3
,它一定是素数,然后用3
把序列的3
的倍数筛掉:
5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, …
取新序列的第一个数5
,然后用5
把序列的5
的倍数筛掉:
7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, …
不断筛下去,就可以得到所有的素数。
用Python来实现这个算法,可以先构造一个从3
开始的奇数序列:
def _odd_iter():
n = 1
while True: # 无限序列
n = n + 2
yield n # 标志着是生成器
注意这是一个生成器,并且是一个无限序列。
然后定义一个筛选函数:
def _not_divisible(n): # lambda为匿名函数
return lambda x: x % n > 0 # x为需要传入的参数,x % n > 0为表达式,表达式的计算结果为返回值
最后,定义一个生成器,不断返回下一个素数:
def primes():
yield 2 # 返回2后暂停
it = _odd_iter() # 初始序列(从3开始)
while True:
n = next(it) # 返回序列的第一个数
yield n # 返回n后暂停
it = filter(_not_divisible(n), it) # 构造新序列(过滤掉当前n的倍数)
关于yield:
- yield和return类似,在函数中用来返回值给调用者
- 使用return的函数是没有状态的,一旦return了,函数就结束了。
- 使用yield的函数是有状态的,返回一个值后,还可以继续调用,直到所有yield都被用完。
这个生成器先返回第一个素数2
,然后,利用filter()
不断产生筛选后的新的序列。
由于primes()
也是一个无限序列,所以调用时需要设置一个退出循环的条件:
# 打印1000以内的素数:
for n in primes():
if n < 1000:
print(n)
else:
break
练习
回数是指从左向右读和从右向左读都是一样的数,例如12321,909。请利用filter()
筛选出回数:
函数实现:
def is_palindrome(n):
L= list(str(n))
k = 0
while(k < len(L)):
if L[k] != L[-(k+1)]:
return False
k += 1
return True
测试:
output = filter(is_palindrome, range(1, 1000))
print('1~1000:', list(output))
if list(filter(is_palindrome, range(1, 200))) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]:
print('测试成功!')
else:
print('测试失败!')
测试结果:
PS D:\MyCode\PythonCode\Test> & D:/Tool/Python/Python311/python.exe d:/MyCode/PythonCode/Test/hello.py
1~1000: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, 212, 222, 232, 242, 252, 262, 272, 282, 292, 303, 313, 323, 333, 343, 353, 363, 373, 383, 393, 404, 414, 424, 434, 444, 454, 464, 474, 484, 494, 505, 515, 525, 535, 545, 555, 565, 575, 585, 595, 606, 616, 626, 636, 646, 656, 666, 676, 686, 696, 707, 717, 727, 737, 747, 757, 767, 777, 787, 797, 808, 818, 828, 838, 848, 858, 868, 878, 888, 898, 909, 919, 929, 939, 949, 959, 969, 979, 989, 999]
测试成功!
4、sorted
Python内置的sorted()
函数就可以对 list 进行排序:
>>> sorted([36, 5, -12, 9, -21])
[-21, -12, 5, 9, 36]
sorted()
函数还可以接收一个key
函数来实现自定义的排序,例如按绝对值大小排序:
>>> sorted([36, 5, -12, 9, -21], key=abs)
[5, 9, -12, -21, 36]
key
指定的函数将作用于 list 的每一个元素上,并根据key
函数返回的结果进行排序。
忽略大小写来比较两个字符串,实际上就是先把字符串都变成大写(或者都变成小写),再比较。
这样,我们给sorted
传入key
函数,即可实现忽略大小写的排序:
>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)
['about', 'bob', 'Credit', 'Zoo']
要进行反向排序,不必改动key
函数,可以传入第三个参数reverse=True
:
>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)
['Zoo', 'Credit', 'bob', 'about']
sorted()
也是一个高阶函数。用sorted()
排序的关键在于实现一个映射函数。
练习
假设我们用一组tuple表示学生名字和成绩:
L = [(‘Bob’, 75), (‘Adam’, 92), (‘Bart’, 66), (‘Lisa’, 88)]
1、请用sorted()
对上述列表分别按名字排序:
函数实现:
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
def by_name(t):
return t[0][0]
测试:
L2 = sorted(L, key=by_name)
print(L2)
测试结果:
PS D:\MyCode\PythonCode\Test> & D:/Tool/Python/Python311/python.exe d:/MyCode/PythonCode/Test/hello.py
[('Adam', 92), ('Bob', 75), ('Bart', 66), ('Lisa', 88)]
2、再按成绩从高到低排序:
函数实现:
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
def by_score(t):
return t[1]
测试:
L2 = sorted(L, key=by_score, reverse=True)
print(L2)
测试结果:
PS D:\MyCode\PythonCode\Test> & D:/Tool/Python/Python311/python.exe d:/MyCode/PythonCode/Test/hello.py
[('Adam', 92), ('Lisa', 88), ('Bob', 75), ('Bart', 66)]
返回函数
1、函数作为返回值
高阶函数除了可以接受函数作为参数外,还可以把函数作为结果值返回。
一个可变参数的求和,可以不返回求和的结果,而是返回求和的函数,后续根据需要再计算。
def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax = ax + n
return ax # sum函数返回变量ax
return sum # lazy_sum函数返回sum函数
调用lazy_sum()
时,返回的并不是求和结果,而是求和函数:
>>> f = lazy_sum(1, 3, 5, 7, 9)
>>> f
<function lazy_sum.<locals>.sum at 0x101c6ed90>
调用函数f
时,才真正计算求和的结果:
>>> f()
25
在函数lazy_sum
中又定义了函数sum
,并且,内部函数sum
可以引用外部函数lazy_sum
的参数和局部变量,当lazy_sum
返回函数sum
时,相关参数和变量都保存在返回的函数中,这种程序结构称为“闭包(Closure)”。
调用lazy_sum()
时,每次调用都会返回一个新的函数,即使传入相同的参数:
>>> f1 = lazy_sum(1, 3, 5, 7, 9)
>>> f2 = lazy_sum(1, 3, 5, 7, 9)
>>> f1==f2
False
f1()
和f2()
的调用结果互不影响。
2、闭包
返回的函数在其定义内部引用了局部变量args
,所以,当一个函数返回了一个函数后,其内部的局部变量还被新函数引用。而且,返回的函数并没有立刻执行,而是直到调用了f()
才执行。
例子:
def count():
fs = []
for i in range(1, 4):
def f():
return i*i
fs.append(f)
return fs
f1, f2, f3 = count()
在上面的例子中,每次循环,都创建了一个新的函数,然后,把创建的3个函数都返回了。
你可能认为调用f1()
,f2()
和f3()
结果应该是1
,4
,9
,但实际结果是:
>>> f1()
9
>>> f2()
9
>>> f3()
9
全部都是9
!原因就在于返回的函数引用了变量i
,但它并非立刻执行。等到3个函数都返回时,它们所引用的变量i
已经变成了3
,因此最终结果为9
。
返回闭包时牢记一点:返回函数不要引用任何循环变量,或者后续会发生变化的变量。
如果一定要引用循环变量,方法是再创建一个函数,用该函数的参数绑定循环变量当前的值,无论该循环变量后续如何更改,已绑定到函数参数的值不变:
def count():
def f(j):
def g():
return j*j
return g
fs = []
for i in range(1, 4):
fs.append(f(i)) # f(i)立刻被执行,因此i的当前值被传入f()
return fs
再看看结果:
>>> f1, f2, f3 = count()
>>> f1()
1
>>> f2()
4
>>> f3()
9
3、nonlocal
使用闭包,就是内层函数引用了外层函数的局部变量。如果只是读外层变量的值,我们会发现返回的闭包函数调用一切正常:
def inc():
x = 0
def fn():
# 仅读取x的值:
return x + 1
return fn
f = inc()
print(f()) # 1
print(f()) # 1
但是,如果对外层变量赋值,Python解释器会把x
当作内部函数fn()
的局部变量,它会报错:
def inc():
x = 0
def fn():
nonlocal x # 声明x不是内层的局部变量,而是外层的局部变量,而x已经在外部函数中初始化了,因此可以进行+1操作
x = x + 1 # 如果没有nonlocal x,x会被打当作内部函数fn()的局部变量,会报错
return x
return fn
f = inc()
print(f()) # 1
print(f()) # 2
Traceback (most recent call last):
File "/home/pyodide/pyscript/_internal.py", line 104, in run_pyscript
result = eval_code(code, globals=__main__.__dict__)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/lib/python311.zip/_pyodide/_base.py", line 468, in eval_code
.run(globals, locals)
^^^^^^^^^^^^^^^^^^^^
File "/lib/python311.zip/_pyodide/_base.py", line 310, in run
coroutine = eval(self.code, globals, locals)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<exec>", line 11, in <module>
File "<exec>", line 6, in fn
UnboundLocalError: cannot access local variable 'x' where it is not associated with a value
原因是x
作为局部变量并没有初始化,直接计算x+1
是不行的。但我们其实是想引用inc()
函数内部的x
,所以需要在fn()
函数内部加一个nonlocal x
的声明。加上这个声明后,解释器把fn()
的x
看作外层函数的局部变量,它已经被初始化了,可以正确计算x+1
。
使用闭包时,对外层变量赋值前,需要先使用nonlocal
声明该变量不是当前函数(内部函数)的局部变量。
练习
利用闭包返回一个计数器函数,每次调用它返回递增整数:
函数实现:
def createCounter():
num = 0
def counter():
nonlocal num
num += 1
return num
return counter
测试:
counterA = createCounter()
print(counterA(), counterA(), counterA(), counterA(), counterA()) # 1 2 3 4 5
counterB = createCounter()
if [counterB(), counterB(), counterB(), counterB()] == [1, 2, 3, 4]:
print('测试通过!')
else:
print('测试失败!')
测试结果:
PS D:\MyCode\PythonCode\Test> & D:/Tool/Python/Python311/python.exe d:/MyCode/PythonCode/Test/hello.py
1 2 3 4 5
测试通过!
匿名函数
有时候不需要显式地定义函数,就可以直接传入匿名函数。Python对匿名函数的支持有限,只有一些简单的情况下可以使用匿名函数。
以map()
函数为例,计算f(x)=x*x
时,除了定义一个f(x)
的函数外,还可以直接传入匿名函数:
>>> list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
[1, 4, 9, 16, 25, 36, 49, 64, 81]
通过对比可以看出,匿名函数lambda x: x * x
实际上就是:
def f(x):
return x * x
关键字lambda
表示匿名函数,冒号前面的x
表示函数参数。在匿名函数中,只能有一个表达式,不用写return,返回值就是该表达式的计算结果。
匿名函数也是一个函数对象,也可以把匿名函数赋值给一个变量,再利用变量来调用该函数:
>>> f = lambda x: x * x
>>> f
<function <lambda> at 0x101c6ef28>
>>> f(5)
25
同样,也可以把匿名函数作为返回值返回,比如:
def build(x, y):
return lambda: x * x + y * y
装饰器(难度较大,尚未完全理解)
由于函数也是一个对象,而且函数对象可以被赋值给变量,所以,通过变量也能调用该函数。
>>> def now():
... print('2015-3-25')
...
>>> f = now
>>> f()
2015-3-25
函数对象有一个__name__
属性(注意:是前后各两个下划线),可以拿到函数的名字:
>>> now.__name__
'now'
>>> f.__name__
'now'
假设我们要增强now()
函数的功能,比如,在函数调用前后自动打印日志,但又不希望修改now()
函数的定义,这种在代码运行期间动态增加功能的方式,称之为“装饰器”(Decorator)。本质上,decorator就是一个返回函数的高阶函数。
定义一个能打印日志的decorator,可以定义如下:
def log(func): # 装饰器接收func函数作为参数
def wrapper(*args, **kw): # 包装器函数,可以接收任意参数的调用
print('call %s():' % func.__name__) # %操作符作用是将其他变量置入字符串特定位置以生成新字符串。类似C中的逗号的作用。在本例中是用后面的func.__name__代替%s中s的位置。
return func(*args, **kw) # 先打印日志,再调用原始函数
return wrapper # 装饰器返回wrapper函数
Python的@
语法,把decorator置于函数的定义处:
@log
def now():
print('2015-3-25')
调用now()
函数,不仅会运行now()
函数本身,还会在运行now()
函数前打印一行日志:
>>> now()
call now():
2015-3-25
把@log
放到now()
函数的定义处,相当于执行了语句:
now = log(now) # log返回一个函数,原来的now函数仍然存在,只是同名的now现在指向了新的函数,所以现在调用now执行的是新的函数,即在log()函数中返回的wrapper()函数
wrapper()
函数的参数定义是(*args, **kw)
,因此,wrapper()
函数可以接受任意参数的调用。在wrapper()
函数内,首先打印日志,再紧接着调用原始函数。
如果decorator本身需要传入参数,那就需要编写一个返回decorator的高阶函数。比如,要自定义log
的文本:(就是在上面的两层嵌套的外外面再套上一层能传输自定义文本的函数,把下面的嵌套改为def Text(text): def log(func): def wrapper*args, **kw): …更有助于理解)
def log(text):
def decorator(func):
def wrapper(*args, **kw):
print('%s %s():' % (text, func.__name__)) # text替换第一个s,func.__name__替换第二个s
return func(*args, **kw)
return wrapper
return decorator
这个3层嵌套的decorator用法如下:
@log('execute') # 比两层嵌套多个字符串参数
def now():
print('2015-3-25')
执行结果如下:
>>> now()
execute now():
2015-3-25
和两层嵌套的decorator相比,3层嵌套的效果是这样的:
>>> now = log('execute')(now)
首先执行log('execute')
,返回的是decorator
函数,再调用返回的函数,参数是now
函数,返回值最终是wrapper
函数。但经过decorator
装饰之后的函数,它们的__name__
已经从原来的'now'
变成了'wrapper'
:
>>> now.__name__
'wrapper'
返回的那个wrapper()
函数名字就是'wrapper'
,所以,需要把原始函数的__name__
等属性复制到wrapper()
函数中,否则,有些依赖函数签名的代码执行就会出错。不需要编写wrapper.__name__ = func.__name__
(原始函数名)这样的代码,Python内置的functools.wraps
就是干这个事的。
一个完整的decorator的写法如下:
import functools # 导入functools模块
def log(func):
@functools.wraps(func) # 将原始函数func的名字等属性复制到将要返回的函数wrapper函数中
def wrapper(*args, **kw):
print('call %s():' % func.__name__)
return func(*args, **kw)
return wrapper
针对带参数的decorator:
import functools
def log(text):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print('%s %s():' % (text, func.__name__))
return func(*args, **kw)
return wrapper
return decorator
练习
请设计一个decorator,它可作用于任何函数上,并打印该函数的执行时间:
函数实现:
# -*- coding: utf-8 -*-
import time, functools
def metric(fn):
@functools.wraps(fn)
def wrapper(*args, **kw):
start = time.time()
fn(*args, **kw)
print('%s executed in %s ms' % (fn.__name__, time.time() - start))
return fn(*args, **kw)
return wrapper
测试:
@metric
def fast(x, y):
time.sleep(0.0012)
return x + y
@metric
def slow(x, y, z):
time.sleep(0.1234)
return x * y * z
f = fast(11, 22)
s = slow(11, 22, 33)
if f != 33:
print('测试失败!')
elif s != 7986:
print('测试失败!')
测试结果:
PS D:\MyCode\PythonCode\Test> & D:/Tool/Python/Python311/python.exe d:/MyCode/PythonCode/Test/hello.py
fast executed in 0.002303600311279297 ms
slow executed in 0.12371063232421875 ms
偏函数
Python的functools
模块提供了很多有用的功能,其中一个就是偏函数(Partial function)。通过设定参数的默认值,可以降低函数调用的难度。 而偏函数也可以做到这一点。
例如,int()
函数可以把字符串转换为整数,当仅传入字符串时,int()
函数默认按十进制转换:
>>> int('12345')
12345
但int()
函数还提供额外的base
参数,默认值为10
。如果传入base
参数,就可以做N
进制的转换:
>>> int('12345', base=8)
5349
>>> int('12345', 16)
74565
假设要转换大量的二进制字符串,可以定义一个int2()
的函数,默认把base=2
传进去:
def int2(x, base=2):
return int(x, base)
>>> int2('1000000')
64
functools.partial
可以帮助创建一个偏函数。functools.partial
的作用就是,把一个函数的某些参数给固定住(也就是设置默认值),返回一个新的函数。
>>> import functools
>>> int2 = functools.partial(int, base=2)
>>> int2('1000000')
64
>>> int2('1010101')
85
新的int2
函数,仅仅是把base
参数重新设定默认值为2
,但也可以在函数调用时传入其他值:
>>> int2('1000000', base=10)
1000000
创建偏函数时,实际上可以接收函数对象、*args
和**kw
这3个参数。
1、当传入:
int2 = functools.partial(int, base=2)
相当于:
kw = { 'base': 2 }
int('10010', **kw)
2、当传入:(假设max函数本来作用的元组是(5, 6, 7))
max2 = functools.partial(max, 10)
实际上会把10作为*args的一部分自动加到左边,相当于:
args = (10, 5, 6, 7)
max(*args) # 结果是10