Python 标准库中的 functools.partial 函数。它的作用是创建一个新的函数,该函数是将指定的函数
以及指定的参数部
分应用后得到的。
示例:
def add(x, y):
return x + y
from functools import partial
# 创建一个新的函数 add_five,将 add 函数的第一个参数设置为 5
add_five = partial(add, 5)
# 使用 add_five 函数
result = add_five(3) # 等价于调用 add(5, 3),结果为 8
print(result) # 输出: 8
上述代码相当于,默认将add函数
的第一个值设置为5.
同时也可以指定参数,例如:
def power(base, exponent):
return base ** exponent
from functools import partial
# 创建一个新的函数 square,将 power 函数的参数 base 设置为 2
square = partial(power, base=2)
# 使用 square 函数
result = square(exponent=3) # 等价于调用 power(base=2, exponent=3),结果为 8
print(result) # 输出: 8