我有一个类有这样的方法
class Validator:
def _is_valid_code(self):
return bool(#some logic here)
def _is_valid_role(self):
return bool(#some logic here)
def _is_valid_age(self):
return bool(#some logic here)
.
.
.
如果所有这些都是 True 我想继续,否则返回一个字符串if not _is_valid_code():
#short circuit and return a string
return "not valid code"
if not _is_valid_role():
#short circuit and return a string
return "not valid role"
if not _is_valid_age():
#short circuit and return a string with description
return "not valid age"
#if we got here the request is valid so return a valid response
return valid_scenario
现在我对此没有任何问题,因为只有三个条件,但是例如,如果我有更多条件,比如说 10 个条件,我最终会得到很多 if 场景,所以我在想是否有这样的事情是可能的,我只是将条件逻辑和条件添加到列表中,就是这样,如果条件为假,问题是获取字符串值conditions = [_is_valid_code(), _is_valid_role(), _is_valid_age()]
if all_conditions_true(conditions):
return valid_scenario
else:
return last_message_before_shortcut
还想知道这是否有效,以及是否可以将其视为 pythonic 并推荐
最佳答案
您可以使用 dict 来存储映射到各自字符串的函数。
checks = {
_is_valid_code: "not valid code",
_is_valid_role: "not valid role",
_is_valid_age: "not valid age",
}
for f in checks:
if not f():
return checks[f]
return valid_scenario
请注意,字典在 Python 3.7+ 中保留插入顺序。如果您使用的是旧版本或想要更严格的排序,请使用 OrderedDict或包含函数和字符串的元组列表。这本身就是完美的 Pythonic,但我不知道上下文,所以我不能肯定你的情况。例如,如果
valid_scenario
不是字符串,我强烈建议使用异常而不是混合返回类型。这个问题包括:Why should functions always return the same type?如果函数正在检查 ,我会推荐相同的错误 状况。
关于python - 函数python的短路列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68278890/