-3

is there a way of having an (yet unkown) function as an argument of a function in python:

def doSomething(<func>):
    #do something with func()

at a later stage, functions could be defined, eg:

def f1(x):
    return x*x

def f2(x):
    return x+1

and I could call now:

doSomething(f1,x1)
doSomething(f2,x1) 
  • why the downvote ? – Newtopian Sep 13 '16 at 13:08
  • 2
    Yes. What happened when you tried? – RemcoGerlich Sep 13 '16 at 13:17
  • 2
    @Newtopian: lack of effort, and it should be on Stack Overflow. Scribbled a short answer anyway because why not, but it's not a good question for here. – RemcoGerlich Sep 13 '16 at 13:24
  • @RemcoGerlich thanks, indeed better for SO, it has in fact already been answered there :-) I was asking mostly for the OP`s sake, I find rude to downvote without (stating) reason, else how are we to correct innapropriate questions if we are not told what is wrong with them. – Newtopian Sep 13 '16 at 13:32
1

Functions are perfectly normal objects in Python, so the answer is yes.

def callFunctionTwice(func, arg):
    func(arg)
    func(arg)

def f(a):
    print(a)

callFunctionTwice(f, "hmm")  # Prints "hmm" twice
0

Somebody answered better than I could at Stack Overflow, be sure to upvote his answer in addition (or instead of) my own if satisfactory.

but for completeness here are the takeaways :

  • define your own class and overload the call method
  • function object have it naturally, just call it to invoke the function
  • Lambda expressions can also get the desired effect

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.