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

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

x = shapes[raw_input()]

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

有帮助吗?

解决方案

几乎。你想要的是

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.

其他提示

我建议使用选择器功能:

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})()
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top