2

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

1
  • The answers you've gotten are correct. There may be better ways to design your game than what you are currently doing. I suggest you step back after you're finished and think about what worked well and what didn't and how the way you coded things makes it easier or harder to add things in the future. Commented Jan 19, 2010 at 8:48

3 Answers 3

3
method = getattr(myPotatoHead, 'play_' + toy)
method()
Sign up to request clarification or add additional context in comments.

1 Comment

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()().
1
getattr(myPotatoHead,"play_"+toy)()

Comments

1

Try this:

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.