带类的字典?

15 投票
2 回答
20945 浏览
提问于 2025-04-15 13:17

在Python中,可以通过字典来创建一个类的实例吗?

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

x = shapes[raw_input()]

我想让用户从菜单中选择,而不是在输入时写很多复杂的if else语句。例如,如果用户输入2,那么x就会是一个新的Circle类的实例。这可能吗?

2 个回答

2

我建议使用一个选择器函数:

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

差不多了。你想要的是

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.

撰写回答