简体   繁体   中英

Passing parameters to a function in switch case using dictionary in python

def doblue (): print "The sea is blue"
def dogreen (): print "Grass is green"
def doyellow (): print "Sand is yellow"

def redflag ():
    print "Red is the colour of fire"
    print "do NOT play with fire"

def errhandler ():
    print "Your input has not been recognised"

set up a dictionary of actions

takeaction = {
"blue": doblue,
"green": dogreen,
"yellow": doyellow,
"red": redflag}

colour = raw_input("Please enter red blue green or yellow ")
takeaction.get(colour,errhandler)()

what if I have to pass some parameters to the doblue() or any function of that kind??

You need to rewrite the doblue and other functions to receive arguments (optional or otherwise) like so

def doblue (item): print "The {} is blue".format(item)

Then you have the change your dispatch code to look like this

takeaction[colour](item). 

This will pass item to your function.

On a more general point, your understanding of how dictionary dispatching works seems to be incomplete based your assumptions in this question. You need to revisit how it works before trying out stuff like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM