简体   繁体   English

python - 将参数传递给字典中的函数

[英]python - pass argument to function in a dictionary

I've something like a switch, that given an option will call a function eg 我有类似开关的东西,给定一个选项会调用一个函数,例如

#... 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]()

I am trying to pass a parameter ( mt ) into my options dict that will call a function, but i'm not being able to do so. 我试图将参数( mt )传递给我将调用函数的选项 dict,但我无法这样做。

if op received is 1 and mt is foo, how the call to the right function (zipcode) will be done by passing mt as a parameter? 如果op收到1并且mt是foo,那么如何通过将mt作为参数传递来完成对右函数(zipcode)的调用?

ideally: options[op](mt) and defining one parameter in the function? 理想情况下: options[op](mt)并在函数中定义一个参数?

Thanks 谢谢

Your code is not indented properly, which is very important in Python and would cause syntax errors as is. 您的代码没有正确缩进,这在Python中非常重要,并且会导致语法错误。

However, what you are suggesting would work perfectly. 但是,你所建议的将是完美的。

Consider the following: 考虑以下:

def multiply(m,n):
    return n*n

def add(m,n)
    return m,n

my_math = { "+":add,
            "*":multiply}

You could then call that as follows: 然后您可以按如下方式调用:

>>> print my_math["+"](1,2)
3
>>> print my_math["*"](4,5)
20

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

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