【发布时间】:2019-08-24 19:03:32
【问题描述】:
假设我有一堂课。这个类里面有两个方法。在该类之外,脚本要求用户输入。如何使用用户的输入来调用类中的方法?我想弄清楚这一点的原因是,如果我曾经在一个文件中有多个类,并且希望用户的输入能够与每个不同类中包含的方法进行交互。
我尝试使用引用类的命令列表,但我想不出似乎没有任何效果。我试图找到这个问题的答案,但我发现的一切都与用户输入调用不在类中的函数有关,我知道该怎么做。
这是我正在尝试做的一个简单示例:
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’”。
你有什么想法?
【问题讨论】: