Dictionary with classes?

In Python, can I instantiate a class through a dictionary?

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

I want the user to select from the menu, not the code, if any expressions were input. For example, if the user entered 2, x will then be a new instance of Circle. Is it possible?

+7
python dictionary class
source share
2 answers

Nearly. Do you want to

 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. 
+23
source share

I would recommend the select 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})() 
+1
source share

All Articles