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
mandroid
2,3586 gold badges24 silver badges38 bronze badges
-
When you tried it, what happened?S.Lott– S.Lott2009年07月30日 18:12:17 +00:00Commented 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 :-/mandroid– mandroid2009年07月30日 18:13:47 +00:00Commented Jul 30, 2009 at 18:13
-
1Yes, 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.Markus– Markus2009年07月30日 18:28:16 +00:00Commented Jul 30, 2009 at 18:28
2 Answers 2
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
Vinay Sajip
100k15 gold badges184 silver badges196 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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})()
Comments
lang-py