Python替代Javascript function.bind()吗?

Mar*_*ark 0 javascript python bind callback

用Javascript可能会写

var ids = ['item0', 'item1', 'item2', 'item3']; // variable length
function click_callback(number, event)
{
    console.log('this is: ', number);
}
for (var k = 0; k < ids.length; k += 1)
{
    document.getElementById(ids[k]).onclick = click_callback.bind(null, k);
}
Run Code Online (Sandbox Code Playgroud)

因此,即使在调用函数k时它已更改,我也可以将其注册时的值传递给回调函数。

Python有办法做一些等效的事情吗?


具体情况是这样(但我更喜欢一个一般性的答案):

我有可变数量的matplotlib图(每个坐标一个)。每个都有一个SpanSelector,出于某种原因,它被设计为仅将两个极限点传递给回调函数。但是,它们都具有相同的回调函数。所以我有:

def span_selected(min, max):
Run Code Online (Sandbox Code Playgroud)

但是我需要

def span_selected(which_coordinate, min, max):
Run Code Online (Sandbox Code Playgroud)

在注册回调时,我当然知道坐标,但是在调用函数时我需要知道它。在Javascript中,我会做类似的事情

callback = span_selected.bind(null, coordinate)
Run Code Online (Sandbox Code Playgroud)

我将在Python中做什么?

Mar*_*ark 5

原来它已经在这里得到回答:如何在Python函数中将参数绑定到给定值?

解决方案是:

from functools import partial
def f(a,b,c):
    print a,b,c
bound_f = partial(f,1)
bound_f(2,3)
Run Code Online (Sandbox Code Playgroud)

计入MattH的全部学分。

编辑:因此在示例中,而不是

callback = span_selected.bind(null, coordinate)
Run Code Online (Sandbox Code Playgroud)

使用

callback = partial(span_selected, coordinate)
Run Code Online (Sandbox Code Playgroud)