Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary with classes?

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?

like image 638
mandroid Avatar asked Jul 30 '09 18:07

mandroid


1 Answers

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.
like image 148
Vinay Sajip Avatar answered Sep 24 '22 15:09

Vinay Sajip