Jan-08-2019, 01:54 PM
(Jan-08-2019, 01:22 PM)buran Wrote: I think your confusion is not with lambda, but with functions altogether. Let's look at your second snippet (fixed for the NameError) and with some additions from medef foo(n,m): return lambda a: a * (n + m) bar = foo(n=11, m=5) print(bar(a=3))on line#4 you supply values for n and m (i.e. arguments for foo() function, not the lambda. Now bar function is effectively the same asdef bar(a): return a * 16and then you call bar(), supplying thea
argument. Now, what you describe as blueprint for function:def my_power(power): return lambda x: x ** power pow2 = my_power(2) # pow2 will get an argument and will raise to power of 2 pow3 = my_power(3) # pow3 will get an argument and will raise to power of 3 print(pow2(2)) # x=2 print(pow3(5)) # x=5Now there are other way to create "blueprints for function"
Output:4 125 >>>from functools import partial def my_power(num, power): return num ** power pow2 = partial(my_power, power=2) pow3 = partial(my_power, power=3) print(pow2(2)) # num=2 print(pow3(5)) # num=5 # and you still can do print(my_power(2, 3))
Output:4 125 8 >>>
That's great - cheers for the in-depth explanation.