electron1
electron1

Reputation: 97

Turn user input strings into a function call

I am in the process of writing a lexer for a text based game. A simplified example of what my code looks like this:

class Character:
    def goWest(self, location):
        self.location == location.getWest() #getWest() would be defined in the location class
x = raw_input("What action would you like to take")

With this code, I would like the player to enter something like: "Go West" and have a separate function take the substring "West", and then call the goWest() method for that Character.

Upvotes: 1

Views: 46

Answers (1)

A.J. Uppal
A.J. Uppal

Reputation: 19264

You should use multiple if statements:

x = raw_input("What action would you like to take")
direction = x.split()[-1].lower()
if direction == "west":
    character.goWest(location)
elif direction == "east":
    character.goEast(location)
elif direction == "north":
    character.goNorth(location)
else:
    character.goSouth(location)

Alternatively, you could alter your go function:

class Character:
    def go(self, direction, location):
        self.location = location
        self.direction = direction
        #call code based on direction

And go about the above as:

x = raw_input("What action would you like to take")
character.go(x.split()[-1].lower(), location)

You could use exec, but exec and eval are very dangerous.

Once you have functions goWest(), goEast(), goNorth(), and goSouth():

>>> func = "go"+x.split()[-1]+"()" #"goWest()"
>>> exec(func)
west

Upvotes: 1

Related Questions