2016-10-03 75 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