问题描述
我想将一个 Python 函数传递给另一个函数,并提前填写"它的一些参数.
I want to pass a Python function to another function with some of its parameters "filled out" ahead of time.
这是我正在做的简化:
def add(x, y):
return x + y
def increment_factory(i): # create a function that increments by i
return (lambda y: add(i, y))
inc2 = increment_factory(2)
print inc2(3) # prints 5
我不想使用某种类型的 args
传递,然后用 *args
分解它,因为我传递的函数 inc2
> into 不知道将 args
传递给它.
I don't want to use some sort of passing of args
and later exploding it with *args
because the function I am passing inc2
into doesn't know to pass args
to it.
对于团队项目来说,这感觉有点太聪明了……有没有更直接或 Pythonic 的方法来做到这一点?
This feels a bit too clever for a group project... is there a more straightforward or pythonic way to do this?
谢谢!
推荐答案
这称为柯里化,或部分应用.您可以使用内置的 functools.partial().像下面这样的东西会做你想做的.
This is called currying, or partial application. You can use the built-in functools.partial(). Something like the following would do what you want.
import functools
def add(x,y):
return x + y
inc2 = functools.partial(add, 2)
print inc2(3)
这篇关于使用部分参数创建 Python 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!