2016-02-03 34 views
0
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" 

设立的行动字典

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

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

,如果我有一些参数传递给doblue()或任何这种功能??使用辞典蟒蛇将参数传递给函数在开关的情况下

+0

请使用StackOverflow的代码示例表示法重新编写代码以使其可读。 – Jakob

+0

'takeaction.get(color,errhandler)(parameters)'如果这是你想要的 – The6thSense

+0

谢谢。有效。 –

回答

0

你需要重写doblue等功能,接收参数(可选或其他方式)像这样

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

然后,你必须改变你的调度代码看起来像这样

takeaction[colour](item). 

这将通过item到您的功能。

从更一般的观点来看,根据您在这个问题中的假设,您对字典调度工作方式的理解似乎并不完整。在尝试这样的东西之前,你需要重新审视它的工作原理。

+0

是否可以在.get()中获取字母数字字符串并根据字母数字字符串调用该函数? –