Dictionary with classes?

前端 未结 2 1307
一生所求
一生所求 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:40

    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})()
    

提交回复
热议问题