我有许多函数,它们结合了位置参数和关键字参数,我想将它们的一个参数绑定到一个给定的值(只有在函数定义之后才知道)。有什么通用的方法吗?
我的第一次尝试是:
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的确切参数,而且不能使用单个函数来绑定我感兴趣的所有函数(因为它们有不同的参数列表)。
f
You probably want the partial function from functools.
partial
>>> 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
As suggested by MattH's answer, functools.partial is the way to go.
functools.partial
However, your question can be read as "how can I implement partial". What your code is missing is the use of ABC1, **kwargs- 2 such uses, actually:
**kwargs
def partial(f, *args, **kwargs): def wrapped(*args2, **kwargs2): return f(*args, *args2, **kwargs, **kwargs2) return wrapped
You can use partial and update_wrapper to bind arguments to given values and preserve __name__ and __doc__ of the original function:
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)