python - 如何在 Python 中使用用户输入调用方法

标签 python input methods

假设我要上课。这个类里面有两个方法。在该类之外,脚本要求用户输入。如何使用用户的输入来调用类中的方法?我想弄清楚这一点的原因是,以防万一我在一个文件中有多个类,并希望用户的输入能够与每个不同类中包含的方法进行交互。

我已经尝试使用引用引用类的命令列表,但我想不出任何有效的方法。我试图找到这个问题的答案,但我找到的所有内容都与用户输入调用不在类中的函数有关,我知道该怎么做。

这是我正在尝试做的一个简单示例:

class Character:
        def __init__(self, attributes = [], *args):
                self.name = attributes[0]
                self.health = attributes[1]

        def HEAL(self):
                self.health = self.health + 5
                return(self.health)

Spell_List = ["HEAL"]

Command_List = {"HEAL":Character}

Player = Character("John", 25)

Command = raw_input("Select an action: ").upper()

for Spell in Spell_List:
        if (Command == Spell):
                Command_Result = Player.Command_List[Command]()
                print(Command_Result)
        else:
                print("Action Not Recognized")

如果我要执行脚本并提供“heal”作为输入,我希望脚本调用 Character 类中的 HEAL 方法。由于以下原因,这将打印出数字 30:

1.) Player 变量声明起始数字为 25。

2.) 该方法会使该数字增加 5。

但是,按照现在编写脚本的方式,脚本会出错并声明以下内容: “AttributeError:角色实例没有属性‘Command_List’”。

你有什么想法?

最佳答案

您可以在您的角色类上创建一个执行 Action 函数,然后您可以在任何需要的地方调用它

def perform_action(self, action, *args, **kwargs):
    actions = { 'HEAL': self.HEAL }
    return actions[action](*args, **kwargs)

然后在你的类之外,你只需使用 Player.perform_action('HEAL')

Command_Result = Player.perform_action(Command)

在使用前添加错误处理

关于python - 如何在 Python 中使用用户输入调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57640792/

相关文章:

python - 如何使用 python 在 Windows 10 中打印当前壁纸路径?

python - 在 python 中模拟用户输入以进行测试

c++ - 使用指针从 for_each 循环访问成员方法

c# - 具有属性的快速 ArgumentNullException。有可能的?

python - 在 OS X 10.6 上安装 scrapy 的问题

Python访问具有动态获取的列名的单元格

python - 将 numpy memmap 刷新到 npy 文件

javascript - 如何使用 useReducer 实现 react 控制输入?

Android 应用程序 - 屏幕键盘输入法

class - 是否可以在 Dart 的类中将方法声明为 final?