Pass a function as a variable with one input fixed

匿名 (未验证) 提交于 2019-12-03 02:01:02

问题:

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'm wanting to pass f to G with the second variable as a fixed parameter.

Right now, I am just declaring a third function h that sets y to a set value. This is what it looks like in some form:

def f(x,y):    something something something    return z;  def G(f):     something something something  def h(x):    c= something    return f(x,c); G(h) 

At some point I was also making y a default parameter that I would change each time.

Neither of these are as readable as if I was somehow able to call

G(f(x,c)) 

that particular syntax doesn't work. What is the best way to do this?

回答1:

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



回答2:

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

The lambda syntax essentially creates an anonymous function that accepts one argument (here called 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.



回答3:

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)



回答4:

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) 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!