繁体   English   中英

如何在python中调用字典中的函数

[英]How to call a function inside a dictionary in python

我正在创建一个python shell脚本,允许用户输入输出字符串的命令。 但是也有一些命令会调用一个函数,比如求助 ,或退出我知道python没有switch case,所以我使用的是字典,因为我不想使用if和else语句

问题:

问题是我不能在字典中使用函数调用我实现它的方式,因为它希望输出一个字符串,所以当我输入帮助时我得到一个错误

    #!/usr/bin/python

    x = 0
    while x == 0:



        def helpCommand():
            print "this will help you"

        switcher = {
           "url": " the url is: ... ",
           "email": " my email is: ...",
           "help": helpCommand,
           "exit": exit,
        }

        choice = raw_input("enter your command choice: ")

        def outputChoice(choice)
            return switcher.get(choice)

        print outputChoice(choice)

我试图通过使用函数调用来解决这个问题,但现在我在尝试调用字符串时遇到错误

 def outputChoice(choice)
                    return switcher[choice]()

TypeError:'str'对象不可调用

如何解决这个问题?

Djizeus对callable()的建议使这很简单。

你的代码组织有点奇怪。 您通常不应该将函数定义放在循环中,因为这会导致在每个循环上重新定义函数,这是毫无意义且低效的。

这是使用Djizeus建议的代码的修改版本。

#!/usr/bin/python

def helpCommand():
    print "this will help you"

switcher = {
    "url": " the url is: ... ",
    "email": " my email is: ...",
    "help": helpCommand,
    "exit": exit,
}

def process_choice(choice):
    item = switcher[choice]
    if callable(item):
        item()
    else:
        print item

x = 0
while not x:
    choice = raw_input("Enter your command choice: ")
    process_choice(choice)
    #other stuff that modifies `x`

如果循环中没有任何内容实际修改x ,你可以摆脱它并使循环进入:

while True:
    choice = raw_input("Enter your command choice: ")
    process_choice(choice)

您可以尝试调用该函数,如果失败,则打印该字符串。 iirc这是pythonic方式 - 请求宽恕然后获得权限(或者在这种情况下,可调用属性)更容易。

def bar():
    print 'foo'

gru = { 'dead': 'beef',
        'foo' : bar}

for what in [ 'dead', 'foo']:
    try:
        gru[what]()
    except TypeError:
        print gru[what]

暂无
暂无

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

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