2009-07-30 63 views
7

在Python中是否可以通過字典實例化一個類?有類的詞典?

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

x = shapes[raw_input()] 

我想讓從菜單中的用戶挑選,而不是代碼龐大,如果輸入else語句。例如,如果用戶輸入2,那麼x將是Circle的新實例。這可能嗎?

+0

當你試了一下,發生了什麼? – 2009-07-30 18:12:17

+0

嗯,我正在做的菜單,只是有一個通用的菜單包裝處理要加載的菜單。我對此很陌生: -/ – mandroid 2009-07-30 18:13:47

+1

是的,這是可能的,而且你正確的做法提供了你想在開始時實例化所有形狀,將實例存儲在字典中,並將其中的一個分配給x 。如果你只想實例化所選的類,或者你打算多次實例化單個形狀,請使用Vinay的答案。 – Markus 2009-07-30 18:28:16

回答

23

差不多。你想要的是

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. 
+0

哇。我不知道我們能做到這一點。這是pythonic。感謝vinay sajip ... – 2011-02-28 06:32:17

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