本文介绍了如何将参数绑定到 Python 函数中的给定值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有许多结合了位置参数和关键字参数的函数,我想将它们的一个参数绑定到给定值(只有在函数定义之后才知道).有没有通用的方法来做到这一点?

I have a number of functions with a combination of positional and keyword arguments, and I would like to bind one of their arguments to a given value (which is known only after the function definition). Is there a general way of doing that?

我的第一次尝试是:

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 的确切参数,并且不能使用单个函数来绑定我感兴趣的所有函数(因为它们具有不同的参数列表).

However, for this I need to know the exact args passed to f, and cannot use a single function to bind all the functions I'm interested in (since they have different argument lists).

推荐答案

>>> 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

这篇关于如何将参数绑定到 Python 函数中的给定值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 22:30