Dictionary with classes?

前端 未结 2 1305
一生所求
一生所求 2021-01-02 06:17

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

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

x = shapes[raw_input()]
         


        
2条回答
  •  一向
    一向 (楼主)
    2021-01-02 06:30

    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.
    

提交回复
热议问题