views:

73

answers:

3

Hi,

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

+3  A: 
method = getattr(myPotatoHead, 'play_' + toy)
method()
Jason Orendorff
thankyouwill be very usefuil
Jasper
If you don't need to reuse the variable method, you don't have to save the result of getattr(), and you can directly do getattrt()().
EOL
+1  A: 
getattr(myPotatoHead,"play_"+toy)()
S.Mark
+1  A: 

Try this:

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

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

Seth