Reputation: 13
Let's say I have a class. Inside of this class are two methods. Outside of that class the script asks for the user's input. How can the user's input be used to call a method within the class? The reason I want to figure this out is in case I ever had multiple classes in a file and wanted the user's input to be able to interact with methods contained in each of the different classes.
I have tried using a list of commands that refer to the class in reference, but nothing I can think of seems to work. I have attempted to find an answer to this question, but everything I find relates to the user's input calling a function not in a class, which I know how to do.
Here is a quick example of what I am trying to do:
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")
If I were to execute the script and provide "heal" as the input, I would expect the script to call the HEAL method within the Character class. This would then print the number 30 for the following reasons:
1.) The Player variable states that the starting number is 25.
2.) The method would increase that number by 5.
However, with the way the script is written right now, the script errors out and states the following: "AttributeError: Character instance has no attribute 'Command_List'".
What are your thoughts?
Upvotes: 1
Views: 655
Reputation: 43300
You can create a perform action function on your character class that you can then call from wherever you need it
def perform_action(self, action, *args, **kwargs):
actions = { 'HEAL': self.HEAL }
return actions[action](*args, **kwargs)
then from outside your class you just use Player.perform_action('HEAL')
.
Command_Result = Player.perform_action(Command)
Add error handling before usage
Upvotes: 3