如何在Python函数中将参数绑定到给定值?

时间:2010-07-06 16:10:43

标签: python

我有许多带位置和关键字参数组合的函数,我想将它们的一个参数绑定到给定值(仅在函数定义之后才知道)。有一般的方法吗?

我的第一次尝试是:

def f(a,b,c): print a,b,c

def _bind(f, a): return lambda b,c: f(a,b,c)

bound_f = bind(f, 1)

但是,为此我需要知道传递给f的确切args,并且不能使用单个函数来绑定我感兴趣的所有函数(因为它们有不同的参数列表)。

4 个答案:

答案 0 :(得分:94)

>>> from functools import partial
>>> def f(a, b, c):
...   print a, b, c
...
>>> bound_f = partial(f, 1)
>>> bound_f(2, 3)
1 2 3

答案 1 :(得分:14)

你可能想要functools的partial功能。

答案 2 :(得分:9)

根据MattH的answer的建议,functools.partial是要走的路。

但是,您的问题可以理解为“我该如何实施partial”。您的代码缺失的是使用*args, **kwargs - 2这样的用途,实际上是:

def partial(f, *args, **kwargs):
    def wrapped(*args2, **kwargs2):
        return f(*args, *args2, **kwargs, **kwargs2)
    return wrapped

答案 3 :(得分:1)

您可以使用partialupdate_wrapper将参数绑定到给定值,并保留原始函数的 __name____doc__

from functools import partial, update_wrapper


def f(a, b, c):
    print(a, b, c)


bound_f = update_wrapper(partial(f, 1000), f)

# This will print 'f'
print(bound_f.__name__)

# This will print 1000, 4, 5
bound_f(4, 5)