且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Python中将字符串输入用作变量调用?

更新时间:2022-06-05 22:23:21

将其分解成小块是最简单的方法,可以在需要添加更多命令时避免失控-尝试解析命令字符串切片会很快变得复杂!相反,请尝试将命令拆分为多个单词,然后将每个单词与您要使用的命令相关联.

Breaking it down into small pieces is the easiest way to keep it from getting out of hand when you need to add more commands -- trying to parse a command string with slices is going to get complicated quickly! Instead, try splitting the command into words, and then associating each word with the thing you want to do with it.

from enum import Enum
from typing import Callable, Dict

class Command(Enum):
   """All the commands the user might input."""
   ADD = "add"
   # other commands go here

class Parameter(Enum):
   """All the parameters to those commands."""
   ITEM = "item"
   # other parameters go here


item = ["Item_name","Price"]


def add_func(param: Parameter) -> None:
    """Add a thing."""
    if param == Parameter.ITEM:
        print(item)

COMMAND_FUNCS: Dict[Command, Callable[[Parameter], None]] = {
    """The functions that implement each command."""
    Command.ADD: add_func,
}

# Get the command and parameter from the user,
# and then run that function with that parameter!
[cmd, param] = input("Enter your message: ").split()
COMMAND_FUNCS[Command(cmd)](Parameter(param))