在Python中是否可以通过字典实例化一个类?
shapes = {'1':Square(), '2':Circle(), '3':Triangle()}
x = shapes[raw_input()]
我想让用户从菜单中选择而不是在输入上编写大量if else语句。例如,如果用户输入2,则x将是Circle的新实例。这可能吗?
答案 0 :(得分:24)
几乎。你想要的是
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.
答案 1 :(得分:1)
我建议使用选择器功能:
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})()