我想在列表中添加一个回调函数,它会导致在适当的时候用一个参数调用回调。但是,我也希望回调也传递给另一个变量。
注意:我习惯于在 C++ 中使用 std::bind
或 boost::bind
,所以我一直在寻找类似的东西。
注意:顺便说一句,这是在 Python 中。
碰撞问题示例:
def collision_callback(hit, hitter)
# doing something relevant...
object = create_object()
collision_callbacks.append(collision_callback(_1, object)) # _1 is a placeholder from C++ lol.
# as you can see here _1 is expected
# to be filled in with the hit object.
最佳答案
您可以使用 lambda
:
>>> def minus(a, b):
... return a - b
...
>>> minus1 = lambda x: minus(x, 1)
>>> minus1(3)
2
或者,您也可以使用 functools.partial
:
>>> minus1 = functools.partial(minus, b=1)
>>> minus1(4)
3
但是一些内置函数不接受关键字参数。然后回到 lambda
。
>>> print(operator.sub.__doc__)
sub(a, b) -- Same as a - b.
>>> minus1 = functools.partial(operator.sub, b=1)
>>> minus1(5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sub() takes no keyword arguments
>>> minus1 = lambda x: operator.sub(x, 1)
>>> minus1(9)
8
如果您预填充前导参数(从第一个参数填充值),这无关紧要:
>>> minus_from_10 = functools.partial(operator.sub, 10)
>>> minus_from_10(7)
3
关于Python 回调函数占位符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19701775/