我想用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()
但是决定选项是否可用的代码相当长,条件应该绑定到方法。我把代码改得更清楚了。你知道吗
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中进行选择的写入方式是什么?你知道吗
如果
choice_
函数返回True
如果成功,False
如果不成功,则可以依次尝试每一个函数,直到其中一个函数成功,只需执行以下操作:因为
or
是短路的,所以表达式一找到返回true的操作数就会结束。你知道吗或者,如果它看起来更优雅,你可以这样写:
any
也会短路,以便在找到真操作数时立即停止。你知道吗这还允许您维护作为此操作一部分的函数选项列表,并按如下方式使用:
如果这是您想要做的,那么您的异常方法中没有什么“错误”。不过,在我看来,它有点静态。你知道吗
不完全了解您的问题,一个可供考虑的选择是如果有帮助的话,提供一个可用函数调用的列表。您可以在列表中存储函数、类和几乎任何您想要的东西。然后您可以随机或选择一个并执行它。你知道吗
将执行foo()或bar()。然后可以通过修改选项列表的内容来添加或删除函数。如果您只想执行列表中的第一个,您可以调用
希望这有帮助。你知道吗
汉努
这是否有效:
相关问题 更多 >
编程相关推荐