15

In Python is it possible to instantiate a class through a dictionary?

shapes = {'1':Square(), '2':Circle(), '3':Triangle()}
x = shapes[raw_input()]

I want to let the user pick from a menu and not code huge if else statements on the input. For example if the user entered 2, x would then be a new instance of Circle. Is this possible?

asked Jul 30, 2009 at 18:10
3
  • When you tried it, what happened? Commented Jul 30, 2009 at 18:12
  • Well I'm doing it with menu's, and just having a generic menu wrapper handle what menu to load up. I'm very new to this :-/ Commented Jul 30, 2009 at 18:13
  • 1
    Yes, it's possible, and you're doing it right PROVIDED you want to instantiate all the shapes once at the beginning, store the instances in the dict and have one of them assigned to x. If you want to only instantiate the selected class, or you plan on instantiating individual shapes multiple times, use something like Vinay's answer. Commented Jul 30, 2009 at 18:28

2 Answers 2

31

Almost. What you want is

shapes = {'1':Square, '2':Circle, '3':Triangle} # just the class names in the dict
x = shapes[raw_input()]() # get class from dict, then call it to create a shape instance.
answered Jul 30, 2009 at 18:14
Sign up to request clarification or add additional context in comments.

Comments

2

I'd recommend a chooser function:

def choose(optiondict, prompt='Choose one:'):
 print prompt
 while 1:
 for key, value in sorted(optiondict.items()):
 print '%s) %s' % (key, value)
 result = raw_input() # maybe with .lower()
 if result in optiondict:
 return optiondict[result]
 print 'Not an option'
result = choose({'1': Square, '2': Circle, '3': Triangle})()
answered Jul 30, 2009 at 21:54

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.