Reputation: 815
I'm curious if it is possible to avoid lambda expressions in the following case.
For example using lambda expression I can simple define a function that returns a lambda exp.
def square_fun(a,b,c):
return lambda x: a*x**2 + b*x + c
After we can call it using:
f = square_fun(1,2,3)
f(1) # here x = 1
How can I get the same behaviour avoiding lambda expression?
for example, square_fun must return another function
def square_fun(a,b,c):
return f...
Upvotes: 1
Views: 73
Reputation: 9607
You can also use functools.partial:
from functools import partial
def square_fun(x, a, b, c):
return a * x ** 2 + b * x + c
f = partial(square_fun, a=1, b=2, c=3)
print(f(1))
# should print 6
Upvotes: 4
Reputation: 4924
In python you can define a function inside another function, so the following snippet should give you the same behavior:
def square_fun(a, b, c):
def result(x):
return a*x**2 + b*x + c
return result
f = square_fun(1, 2, 3)
print(f(1))
# Should print 6
So, I'll try to explain what's going on here:
f = square_fun(1, 2, 3)
, f
will actually be mapped to the internal function (aka. result
)return result
does not have the ()
at the end, hence the function is not called yetprint(f(1))
and the variable x
takes 1
as its valuex
, and a
, b
and c
(from square_fun(1, 2, 3)
)You can find additional info here => https://www.learnpython.org/en/Closures
Upvotes: 7