我有一个类似开关的东西,给定一个选项将调用一个函数,例如
#... capture option
op = getOption()
#.. capture metric
mt = getMetric()
def zipcode():
print "You typed zero.\n"
def desc():
print "n is a perfect square\n"
def address():
print "n is an even number\n"
#call desired option
options= {0 : zipcode,
1 : code,
2 : desc,
3 : address
}
options[op]()
我正在尝试将参数(mt)传递到我的选项字典中,该字典将调用函数,但我无法这样做。
如果收到的 op 是 1 并且 mt 是 foo,如何通过传递 mt 作为参数来调用正确的函数(zipcode)?
理想情况下:options[op](mt)
并在函数中定义一个参数?
谢谢
最佳答案
您的代码缩进不正确,这在 Python 中非常重要,并且会导致语法错误。
但是,您的建议非常有效。
考虑以下因素:
def multiply(m,n):
return n*n
def add(m,n)
return m,n
my_math = { "+":add,
"*":multiply}
然后您可以按如下方式调用它:
>>> print my_math["+"](1,2)
3
>>> print my_math["*"](4,5)
20
关于python - 将参数传递给字典中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29088813/