使用部分参数创建Python函数 [英] Creating Python function with partial parameters

查看:67
本文介绍了使用部分参数创建Python函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆