如何将参数绑定到Python函数中的给定值?
问题描述:
我有一些函数结合了位置和关键字参数,我想将它们的一个参数绑定到一个给定的值(仅在函数定义之后才知道)。有没有这样做的一般方法?如何将参数绑定到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
确切指定参数时,并不能使用同一个函数来约束所有我感兴趣的功能(因为他们有不同的参数列表)。
答
>>> 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
答
至于建议的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
答
您可以使用partial
和update_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)