有类的字典?

man*_*oid 8 python dictionary class

在Python中是否可以通过字典实例化一个类?

shapes = {'1':Square(), '2':Circle(), '3':Triangle()}

x = shapes[raw_input()]
Run Code Online (Sandbox Code Playgroud)

我想让用户从菜单中选择,而不是在输入上编写大量if else语句.例如,如果用户输入2,则x将是Circle的新实例.这可能吗?

Vin*_*jip 24

几乎.你想要的是什么

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.
Run Code Online (Sandbox Code Playgroud)