使用部分参数创建Python函数 [英] Creating Python function with partial parameters
问题描述
我想将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
的函数不知道将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.
对于小组项目来说,这有点太聪明了……是否有更简单或更Python的方式来做到这一点?
This feels a bit too clever for a group project... is there a more straightforward or pythonic way to do this?
谢谢!
推荐答案
这称为currying或部分应用程序.您可以使用内置的 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函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!