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