简体   繁体   English

在python中使用字典将参数传递给开关情况下的函数

[英]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?? 如果我必须将一些参数传递给doblue()或任何此类函数该怎么办?

You need to rewrite the doblue and other functions to receive arguments (optional or otherwise) like so 您需要重写doblue和其他函数以接收参数(可选或其他方式),如下所示

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. 这会将item传递给您的功能。

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. 您需要重新尝试一下它的工作原理,然后再尝试这种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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