gpt4 book ai didi

python - python中处理一系列函数检查的最佳/习惯用法是什么

转载 作者:行者123 更新时间:2023-12-01 02:33:46 25 4
gpt4 key购买 nike

我想问一下 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 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

如果apply_function()中需要检查的函数超过10个,有没有更好的处理方法?

这可能对我有用

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

异常是表示检查失败的理想方法,该函数告诉调用者它无法返回结果,因为尚未满足这样做的条件。如果没有发生异常,您可以相信返回值是正确的。

请注意,函数只是对象,因此给定它们的名称,您可以将它们放入序列中并迭代它们。您也可以使用一些寄存器添加更多函数来尝试全局列表。

关于python - python中处理一系列函数检查的最佳/习惯用法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46485154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com