0
What is need for sending function as argument .We can simply call one function from other function and get the result?
2 odpowiedzi
+ 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.
+ 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.