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

use*_*454 60 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)
Run Code Online (Sandbox Code Playgroud)

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

Mat*_*ttH 102

>>> 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
Run Code Online (Sandbox Code Playgroud)

  • @MarkRansom 您可以使用命名参数来绑定任何参数。示例:“部分(f,b = 2)”。 (3认同)
  • 如果你想绑定第二个或第三个参数,有没有办法使用“partial”? (2认同)

Dan*_*man 16

你可能想要partialfunctools 的功能.


Ela*_*zar 9

正如MattH的答案所暗示的那样,functools.partial是要走的路.

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

def partial(f, *args, **kwargs):
    def wrapped(*args2, **kwargs2):
        return f(*args, *args2, **kwargs, **kwargs2)
    return wrapped
Run Code Online (Sandbox Code Playgroud)


Moh*_*eid 7

您可以使用partialandupdate_wrapper将参数绑定到给定值并保留 原始函数的__name__and :__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)
Run Code Online (Sandbox Code Playgroud)