函数的partial应用
典型的,函数在执行时,要带上所有必要的参数进行调用。然后,有时参数可以在函数被调用之前提前获知。这种情况下,一个函数有一个或多个参数预先就能用上,以便函数能用更少的参数进行调用。
举例如下:
from functools import partial def add(a, b): return a + b print(add(1, 3)) plus3 = partial(add, 3) plus4 = partial(add, 3, 5) def plus5(x): return (partial(add, 9))(x) print(plus5(-5)) print(plus3(8)) print(plus4())
结果是:
C:Python35python.exe C:/fitme/work/nltk/1.py 4 4 11 8 Process finished with exit code 0
实际上,我们剋有认为,partial是这么定义的:
def partial(func, *part_args): def wrapper(*extra_args): args = list(part_args) args.extend(extra_args) return func(*args) return wrapper
修改一下我们的代码:
def wcfpartial(func, *part_args): def wrapper(*extra_args): args = list(part_args) args.extend(extra_args) return func(*args) return wrapper def add(a, b): return a + b print(add(1, 3)) plus3 = wcfpartial(add, 3) plus4 = wcfpartial(add, 3, 5) def plus5(x): return (wcfpartial(add, 9))(x) print(plus5(-5)) print(plus3(8)) print(plus4())
运行后,返回结果是一样的。
在中间加两行,打印一下中间值,就更清晰了:
def wcfpartial(func, *part_args): def wrapper(*extra_args): args = list(part_args) print(args) args.extend(extra_args) print(args) return func(*args) return wrapper
extra_args
is something that passed by the partial caller, in the example with p = partial(func, 1); f(2, 3, 4)
it is (2, 3, 4)
.