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"
设置 Action 字典
takeaction = {
"blue": doblue,
"green": dogreen,
"yellow": doyellow,
"red": redflag}
colour = raw_input("Please enter red blue green or yellow ")
takeaction.get(colour,errhandler)()
如果我必须将一些参数传递给 doblue() 或任何此类函数怎么办?
最佳答案
您需要重写 doblue
和其他函数来接收参数(可选或其他),如下所示
def doblue (item): print "The {} is blue".format(item)
然后你可以将你的调度代码更改为如下所示
takeaction[colour](item).
这会将 item
传递给您的函数。
更一般地说,根据您在这个问题中的假设,您对字典调度如何工作的理解似乎是不完整的。在尝试这样的东西之前,您需要重新审视它的工作原理。
关于python - 在python中使用字典将参数传递给switch case中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35176739/