Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

python - Pass a function as a variable with one input fixed

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...