Creating a copy of a function with some vars fixed

Assume I have a function

def multiply_by(x, multiplier):
    return x * multiplier

How can I create a copy of that function and fix the multiplier in that function?

multiply_by_5 = multiply_by?    <-- here I need python magic

such that multiply_by_5 would have only one argument x and the multiplier would be 5? So that

multiply_by_5(2)
10

Is there a way in Python 2.7 to do that?


您可以使用带关键字参数的functools.partial

>>> def multiply_by(x, multiplier):
...     return x * multiplier
...
>>> from functools import partial
>>> multiply_by_5 = partial(multiply_by, multiplier=5)
>>> multiply_by_5(2)
10

functools.partial is made exactly for this.

you can use it like

import functools
multiply_by_5=functools.partial(multiply_by,multiplier=5)

As suggested by @niemmi's answer, functools.partial is probably the way to go.

However, similar work can be done using curried functions:

def multiply_by(multiplier):
    def multiply(x):
        return multiplier * x
    return multiply

>>> multiply_by_5 = multiply_by(5)    # no magic
>>> multiply_by_5(2)
10

Or using the lambda syntax:

def multiply_by(multiplier):
    return lambda x: multiplier * x

Note that partial is more succinct, more efficient, and more directly express your intent in a standard way. The above technique is an example of the concept called closure, which is means that a function defined in inner scope may refer to variables defined in enclosing scopes, and "close" over them, remembering them, and even mutating them.

Since this technique is more general, it might take the reader of your code more time to understand what exactly do you mean in your code, since your code may be arbitrarily complicated.


Specifically for multiplication (and other operators) partial can be combined with operator.mul :

>>> import functools, operator
>>> multiply_by_5 = functools.partial(operator.mul, 5)
>>> multiply_by_5(2)
10
链接地址: http://www.djcxy.com/p/51122.html

上一篇: 在Python中理解内部自我

下一篇: 创建一个固定了一些变量的函数的副本