我可以通过输入字符串来调用函数吗?
Can I call a function by inputting a string?
我想做一个当文本输入等于命令时可以调用的函数。
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行是否可以调用函数?我想象它的工作方式是它会找到键 'possibility' 的条目,然后将其作为函数调用,但我不确定。
如果前面的代码不起作用,怎么办?
假设在您的代码中有一个名为 help
、clear
、...的函数。
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)
我想 '/commands'
在 command_dict
中的值(command
函数)应该更改为另一个函数。如果您键入 'commands',程序将崩溃。
我想做一个当文本输入等于命令时可以调用的函数。
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行是否可以调用函数?我想象它的工作方式是它会找到键 'possibility' 的条目,然后将其作为函数调用,但我不确定。
如果前面的代码不起作用,怎么办?
假设在您的代码中有一个名为 help
、clear
、...的函数。
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)
我想 '/commands'
在 command_dict
中的值(command
函数)应该更改为另一个函数。如果您键入 'commands',程序将崩溃。