0

What is need for sending function as argument .We can simply call one function from other function and get the result?

3rd Jun 2017, 6:49 AM
shudhatma
shudhatma - avatar
2 ответов
+ 14
You can call a function directly within the brackets of another function call. Or you can pass a reference to a function to another function call. def addOne(x): return x+1 def timesThree(x): return x*3 print(timesThree(addOne(1))) #Prints 6- 1+1= 2, 2*3= 6 you can see we passed a call to addOne into the parameters of timesThree, which itself is passed as an argument to the print function. another way could be this: def addThenTimes(x, addFunc, timesFunc): return timesFunc(addFunc(x)) x = addThenTimes(1,addOne, timesThree) print(x) #This still prints 6 What we've done here is pass a reference to addOne and timesThree to our new function without calling it. Inside the new function, addThenTimes, we call the references to addOne and timesThree which use the first method we looked at.
3rd Jun 2017, 7:23 AM
Aidan Haddon-Wright
Aidan Haddon-Wright - avatar
+ 1
one neat example is map function. filter and reduce also fall in this category. list/set/tuple comprehension is another example. all these take function as one of their arguments.
3rd Jun 2017, 7:20 AM
Venkatesh Pitta
Venkatesh Pitta - avatar