Python function (or set of functions) as input of a function or class

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) 

4

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

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

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *