Pass a function as a variable with one input fixed

前端 未结 4 1595
庸人自扰
庸人自扰 2020-12-19 12:16

Say I have a two dimensional function f(x,y) and another function G(function) that takes a function as an input. BUT, G only takes one dimensional functions as input and I\

相关标签:
4条回答
  • 2020-12-19 12:47

    An ideal solution would use partial application, but the quickest and easiest way to accomplish this would be to wrap f inside a lambda statement like this:

    G(lambda x: F(x, C))
    

    In this example, the lambda syntax creates an anonymous function that accepts one argument, x, and calls f with that value x and the constant C. This works because the value of C is "captured" when the lambda is created and it becomes a local constant inside the lambda.

    0 讨论(0)
  • 2020-12-19 12:49

    What you are looking for is called a closure.

    def make_h(c):
       def h(x):
           return f(x, c)
       return h
    

    Now if you assign h = make_h(c), then h(x) equals f(x, c), and you can pass your h to G.

    If you wish, the functools library has support for closures (functools.partial)

    0 讨论(0)
  • 2020-12-19 12:51

    The functools.partial function can be used to do this (note, it's not entirely clear where c comes from in your example code, so I've assumed it's some constant).

    import functools
    
    def f(x,y):
        return x+y
    
    c = 3
    
    G = functools.partial(f, c)
    G(4)
    

    I think this is more explicit than the lambda approaches suggested so far.

    Edit: replacing the right most argument is not possible as we are dealing with positional arguments. Depending on the level of control available, you could introduce a wrapper which handles the switching:

    import functools
    
    def f(x,y):
        return x+y
    
    def h(c,y):
        return f(y,c)
    
    c = 3
    
    G = functools.partial(h, c)
    G(4)
    

    But I think you start to sacrifice readability and maintainability at this point...

    0 讨论(0)
  • 2020-12-19 12:59

    Try this:

    def h():
        return lambda x: f(x,c)
    

    No need to supply the x to h - you could pass a function to wrap eventually if it wouldn't be in the scope. In fact, h is obsolete unless you want it to work with any 2-argument function:

    def h(functionToWrap, fixedSecondArgument):
         return lambda x: functionToWrap(x, fixedSecondArgument)
    
    0 讨论(0)
提交回复
热议问题