python - Can I assign a function to a variable for use within another function? -


i want know if can create function within it's arguments can define function use else? eg:

def askquestion(functionname):     userinput == str(input("are sure want run this? <y/n> "))     if userinput = "y":         functionname()     elif userinput == "n":         print("returning main menu")     else:         print("that not valid input!") 

i dont know if explained if me out great.

yes, can. pass in function object:

def foo():     # foo  def bar():     # bar  askquestion(foo)  # run foo when `y` typed. 

python functions first-class objects, assigned whatever name defined begin can bind them other names too.

you can, example, store them in mapping, functions in mapping based on variable altogether:

map = {     'spam': foo,     'eggs': bar, }  askquestion(map[anothervar]) 

within askquestion, functionname bound whatever function object passed in. adding () after name invokes function.

you can pass in arguments too, all functions pass in have have same signature. wrap function in lambda or other function object pass in arguments, or take @ functools.partial() generate callables pre-defined arguments.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -