python - Assigning a function (which is assigned dynamically) along with specific parameters, to a variable. -
ok, here's deal, have function( take_action ), calls function. don't know function take_action going call.
i had part figured out this question, thing is, on question deal functions take no arguments, take_action take 1 of several different functions quite different each other, different actions taken, different arguments.
now example code:
def take_action(): action['action']() #does other stuff 'other_stuff_in_the_dic' def move(x,y): #stuff happens action = {'action': move, 'other_stuff_in_the_dic': 'stuff' }
(in case 'action' move, said, that's assigned dynamically depending on user input)
what do, this:
action = { 'action': move(2,3), 'other_stuff': 'stuff' }
(obviously calls function there, since has (), hence wouldn't work)
i'm beginner programmer, , thing thought of using list, in key inside dic, pass 1 list argument, instead of each content of list being passed on argument.
what way achieve this, 'action' key (or dictionary on key?) stores arguments should use when call on take_action?
use functools.partial()
store functions arguments:
from functools import partial action = {'action': partial(move, 2, 3), 'other_stuff': 'stuff'}
calling action['action']()
results in move(2, 3)
being called.
Comments
Post a Comment