很多选择之间切换正确的方式我想写点东西像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