Pass a function as a variable with one input fixed

前端 未结 4 1601
庸人自扰
庸人自扰 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: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)

提交回复
热议问题