【问题标题】:Can I call a function by inputting a string?我可以通过输入字符串来调用函数吗?
【发布时间】:2015-12-04 15:38:24
【问题描述】:

我想做一个可以在文本输入等于命令时调用的函数。

from os import system
from time import sleep
import ctypes

ctypes.windll.kernel32.SetConsoleTitleW('SimpleChat')

print('Hi, welcome to my basic chat engine!')

sleep(5)

system('cls')

username = input('Enter a username: ')

ctypes.windll.kernel32.SetConsoleTitleW('SimpleChat - ' + username)

system('cls')

def commands (command):
    commandlist = ['/help','/clear', '/commands']
    commanddict = {'/help' : 'help', '/clear' : 'clear', '/commands' : 'commands'}
    for possibility in commandlist:
        if command == possibilty:
            commanddict[possibility]()
            break 

def textInput (text):
    if text[0] == '/':
        commands(text)

第 24 行可以调用函数吗?我想象它会起作用的方式是它会找到键“可能性”的条目,然后将其作为函数调用,但我不确定。

如果前面的代码不起作用,会怎样?

【问题讨论】:

  • 如果您有函数helpclearcommands 在范围内,您可以将它们粘贴到字典中:{"/help": help, "/clear": clear} 并像以前一样调用它们。不过保留两个列表没有意义:if command not in commanddict: print("no such command")
  • 命令中的 dict 值应该是实际的 help 函数(helpclearcommands 等等 - 不带括号)。是的,它会起作用。 commanddict[possibility] 解析为函数对象,可以通过附加() 来调用。因此,除了创建 commanddict 之外,您的代码也非常好。
  • “第 24 行调用函数有效吗?” 运行时有效吗?
  • @三十二上校:谢谢,我没有意识到'in'可以这样使用。另外,按照您的解释方式,显示不带引号的“帮助”的部分将其称为函数,不是吗?因此,我需要为每个命令创建一个函数吗?
  • @Kevin,我还没有实现这些命令,因为我不确定我想怎么做,因此无法测试它。

标签: python function dictionary call


【解决方案1】:

假设您的代码中有一个名为helpclear、...的函数,如下所示。

def help():
    print("help!")

然后,下面的commands 函数将执行您想要的操作。 请注意,函数可以用作 Python 中字典的值。

def commands (command):
    command_dict = {'/help' : help, '/clear' : clear, '/commands' : commands}
    func = command_dict.get(command)

    if func is not None:
        func()
    else:
        print("I don't have such a command: %s" % command)

我猜command_dict 中的'/commands' 的值(command 函数)应该更改为另一个函数。如果您键入“命令”,程序将崩溃。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-19
    • 1970-01-01
    • 2019-03-06
    • 1970-01-01
    相关资源
    最近更新 更多