python中处理一系列函数检查的最佳方法是什么
我想问一下python中处理这种代码逻辑的最佳方法是什么python中处理一系列函数检查的最佳方法是什么,python,if-statement,idioms,Python,If Statement,Idioms,我想问一下python中处理这种代码逻辑的最佳方法是什么 list_a = [] def func_a(): if some check not pass return False # check pass add some stuff to list_a and return True def func_b(): if some check not pass return False # check pass add some stuff t
list_a = []
def func_a():
if some check not pass
return False
# check pass
add some stuff to list_a and return True
def func_b():
if some check not pass
return False
# check pass
add some stuff to list_a and return True
def func_c():
if some check not pass
return False
# check pass
add some stuff to list_a and return True
def apply_function():
if fun_a():
return list_a
if fun_b():
return list_a
if fun_c():
return list_a
...
return list_a #empty list
如果有超过10个函数需要签入apply\u function()
,是否有更好的处理方法
这也许对我有用
If funcA() or funcB() or funcC():
return list_a
return list_a
在这种情况下是否可以使用any()
谢谢。不要更改全局设置。如果检查失败,让函数返回列表或引发异常。这样,您可以只返回函数的结果,或者如果引发异常,则继续下一步
def func_a():
if some check not pass
raise ValueError('....')
# check pass
return [some, list]
# further functions that apply the same pattern.
def apply_function():
for f in (func_a, func_b, func_c):
try:
return f()
except ValueError:
# check didn't pass, continue on to the next
pass
异常是这里表示检查失败的理想方法,函数告诉调用方它无法返回结果,因为不满足返回结果的条件。如果没有发生异常,您可以相信返回值是正确的
请注意,函数只是对象,因此给定它们的名称,您可以将它们放在序列中并对其进行迭代。您也可以使用一些寄存器添加更多函数来尝试全局列表。将内容添加到
列表\u a
更麻烦,因为它是一个超出外部范围的列表,这引入了状态的概念。谢谢。该程序最初用于穷举所有情况,func_b将检查比func_a更松散的情况,并检查不同的情况。