Pass a function as a variable with one fixed input

Let's say that I have a two-dimensional function f (x, y) and another function G (function), which takes the function as input. BUT, G takes only one-dimensional functions as input, and I want to pass f to G with the second variable as a fixed parameter.

Now I just declare the third function h, which sets y to the given value. Here's how it looks in one form or another:

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 also made y the default parameter, which I would change every time.

None of them read as if I could call

G(f(x,c))

this particular syntax does not work. What is the best way to do this?

+4
source share
4 answers

, f :

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

, ( x f x C). , C "", .

+4

functools.partial ( : , c , , ).

import functools

def f(x,y):
    return x+y

c = 3

G = functools.partial(f, c)
G(4)

, , -.

: , . , :

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)

, ...

+4

, , .

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

, h = make_h(c), h(x) f(x, c), h G.

, functools (functools.partial)

+2

:

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

No need to deliver xbefore h- you can pass in a function that will later be completed if it is not in the scope. In fact, it is hdeprecated if you do not want it to work with any function with two arguments:

def h(functionToWrap, fixedSecondArgument):
     return lambda x: functionToWrap(x, fixedSecondArgument)
+1
source

Source: https://habr.com/ru/post/1528866/


All Articles