很多選擇之間切換正確的方式我想寫點東西像AI在Python:什麼是Python中
我的第一個碼是這樣的:
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()
但代碼來決定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
當越來越多的選擇,進入我的代碼,它變得越來越混亂和醜陋,我考慮過使用
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中進行選擇的寫入方式?
可以重寫選項2作爲'choice_a()或choice_b()或choice_c()' – khelwood
從另一個問題,檢查我的答案是:http://stackoverflow.com/a/39816814/847552。我希望它能幫助你。 – skovorodkin
我真的不喜歡通過異常工作,因爲這意味着你正在編碼知道它會破壞的東西。如果你編程的權利,它不應該拋出一個錯誤....所以不是第三種選擇。我想說,你通常應該在運行你的方法之前驗證關鍵變量,所以我個人喜歡2。這是因爲該方法比選項1更自足。但是...我標記這是因爲它是一個基於意見的問題,我給你我的* 0.02 * – Fallenreaper