繁体   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"

建立行动字典

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传递给您的功能。

从更笼统的角度来看,根据您对该问题的假设,您对字典调度工作原理的理解似乎并不完整。 您需要重新尝试一下它的工作原理,然后再尝试这种方法。

暂无
暂无

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

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