Dictionary with classes?

2019-02-12 21:54发布

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?

2条回答
爷、活的狠高调
2楼-- · 2019-02-12 22:31

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})()
查看更多
趁早两清
3楼-- · 2019-02-12 22:52

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.
查看更多
登录 后发表回答