Jasper
Jasper

Reputation:

Variables as a part of calling a method in python

I'm pretty new to programming and I'm creating a python game for my little sister.

I'm having trouble, because I want the variable value to be a part of the method name Is there any way this is possible?

def play_with_toy(self):
    toy = gui.buttonbox(
        msg = 'Choose a toy for your potato head to play with:',
        title = 'Choose a Toy',
        choices = self.toys)
    method_name = 'play_' + toy + '()'
    myPotatoHead.method_name

Using Python 2.5.4 for Mac (IDLE) and easygui 0.83

Thanks for any help

Upvotes: 2

Views: 181

Answers (3)

Seth
Seth

Reputation: 46473

Try this:

method = getAttr(myPotatoHead, 'play_' + toy)
method()

(sorry about the semi-colons! I was programming in javascript all day).

Upvotes: 1

YOU
YOU

Reputation: 123937

getattr(myPotatoHead,"play_"+toy)()

Upvotes: 1

Jason Orendorff
Jason Orendorff

Reputation: 45126

method = getattr(myPotatoHead, 'play_' + toy)
method()

Upvotes: 3

Related Questions