2016-10-03 66 views
2

很多選擇之間切換正確的方式我想寫點東西像AI在Python:什麼是Python中

  1. 我的第一個碼是這樣的:

    def run() 
        if choice_a_is_avilable: 
         choice_a() 
         return 
        elif choice_b_is_avilable: 
         if choice_b_1_is_avilable: 
          choice_b_1() 
          return 
         elif choice_b_2_is_avilable: 
          choice_b_1() 
          return 
        else: 
         choice_c() 
    
    while 1: 
        run() 
    
  2. 但代碼來決定choice_a_is_avilable是否相當長,條件應該綁定到方法。我更改了代碼以使其更清楚。

    def run(): 
        if(choice_a()): 
         return 
        elif(choice_b()): 
         return 
        else(choice_c()): 
         return 
    
    def choice_b(): 
        if choice_b_is_avilable: 
         if(choice_b_1()): 
          return True 
         elif(choice_b_2) 
          return True 
    
        return False 
    
  3. 當越來越多的選擇,進入我的代碼,它變得越來越混亂和醜陋,我考慮過使用Exception

    class GetChoiceException(Exception): 
        """docstring for GetChoiceException""" 
        def __init__(self, *args): 
         super(GetChoiceException, self).__init__(*args) 
    
    
    def run(): 
        try: 
         choice_a() 
         choice_b() 
         choice_c() 
        except GetChoiceException: 
         pass 
    
    def choice_a(): 
        if choice_a_is_avilable: 
         some_function() 
         raise GetChoiceException() 
    

它是一種Exception虐待?

什麼是在Python中進行選擇的寫入方式?

+0

可以重寫選項2作爲'choice_a()或choice_b()或choice_c()' – khelwood

+0

從另一個問題,檢查我的答案是:http://stackoverflow.com/a/39816814/847552。我希望它能幫助你。 – skovorodkin

+0

我真的不喜歡通過異常工作,因爲這意味着你正在編碼知道它會破壞的東西。如果你編程的權利,它不應該拋出一個錯誤....所以不是第三種選擇。我想說,你通常應該在運行你的方法之前驗證關鍵變量,所以我個人喜歡2。這是因爲該方法比選項1更自足。但是...我標記這是因爲它是一個基於意見的問題,我給你我的* 0.02 * – Fallenreaper

回答

0

如果您choice_函數返回True如果成功,False如果不成功,那麼你可以嘗試每個反過來,直到一個是成功的根本:

choice_a() or choice_b() or choice_c() 

因爲or短路,表達將完成只要它找到一個返回true的操作數。

或者,如果它看起來更優雅,你可以寫這樣的:

any(x() for x in (choice_a, choice_b, choice_c)) 

any也是短路,因爲它找到一個操作數是真實儘快停止。

這也將讓你保持的功能選擇,此部分操作的列表,並使用它像這樣:

choices = [choice_a, choice_b, choice_c] 
... 
any(x() for x in choices) 
+0

我喜歡這個,但是我擔心有關副作用的任何問題。 –

0

沒有什麼「錯誤」在你的異常的方法,如果這是什麼你想要做的。但對我來說,它看起來有點靜態。

不完全知道你的問題,一個可供選擇的考慮是有一個可用的函數調用列表,如果它有幫助。你可以存儲函數,類和幾乎任何你想要的列表。然後你可以隨機選擇一個或選擇一個並執行。

from random import choice 

def foo(): 
    print "foo" 

def bar(): 
    print "bar" 

options = [foo,bar] 
x = choice(options) 
x() 

將執行foo()或bar()。然後可以通過修改選項列表的內容來添加或刪除功能。如果你只是想執行列表中的第一個,你會打電話

options[0]() 

希望這會有所幫助。

哈努哈利

0

將這項工作:

choices = {'a': 1, 'b': 2} 
result = choices.get(key, 'default') 
0

我表驅動程序的大風扇。

ctrl_table = [ 
    [choice_a_test, choice_a_func], 
    [choice_b_test, choice_b_func], 
    [choice_c_test, choice_c_func]] 

for test, func in ctrl_table: 
    if test(): 
     func() 
     break