使用部分参数创建Python函数

时间:2022-05-10 11:00:43

I want to pass a Python function to another function with some of its parameters "filled out" ahead of time.

我想将Python函数传递给另一个函数,其中一些参数提前“填写”。

This is simplification what I am doing:

这简化了我正在做的事情:

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

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.

我不想使用某种类型的args传递,然后使用* args进行爆炸,因为我传递inc2的函数不知道将args传递给它。

This feels a bit too clever for a group project... is there a more straightforward or pythonic way to do this?

对于一个团队项目来说,这感觉有点过于聪明......有没有更简单或pythonic的方式来做到这一点?

Thanks!

1 个解决方案

#1


19  

This is called currying, or partial application. You can use the built-in functools.partial(). Something like the following would do what you want.

这称为currying或部分应用。您可以使用内置的functools.partial()。像下面这样的东西会做你想要的。

import functools
def add(x,y):
    return x + y

inc2 = functools.partial(add, 2)
print inc2(3)

#1


19  

This is called currying, or partial application. You can use the built-in functools.partial(). Something like the following would do what you want.

这称为currying或部分应用。您可以使用内置的functools.partial()。像下面这样的东西会做你想要的。

import functools
def add(x,y):
    return x + y

inc2 = functools.partial(add, 2)
print inc2(3)