什么是编写包含多个条件的验证函数的推荐结构?请看这两个例子。第一个看起来很丑,第二个并不常见,可能是因为通常使用"assert"来排除意外行为。是否有更好的替代方案?
建议结构:使用单独的函数来处理每个条件,然后将它们组合在一起以进行验证。这样可以使代码更易于理解和维护。
或者
def validate(val):
if cond1(val):
return False
if cond2(val):
return False
if cond3(val)
return False
return True
或者
def validate(val):
try:
assert cond1(val)
assert cond2(val)
assert cond3(val)
return True
except AssertionError:
return False
assert
来验证数据!它用于验证程序的逻辑:您使用它来测试某些条件,如果您的程序逻辑正确,这些条件将永远不会发生。如果程序引发AssertionError
,那么就意味着您的代码存在错误并需要调试。 - PM 2Ring