【发布时间】:2021-07-09 22:43:37
【问题描述】:
我有一个类有这样的方法
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
还想知道这是否有效,是否可以被视为 Python 并推荐
【问题讨论】:
-
创建方法/错误字符串对列表。然后遍历该列表,调用该方法,如果失败,则返回字符串。将其设为类变量,这样实际上可以为您节省大量时间
-
如果发生错误,我不会返回字符串。让每个函数要么返回有效场景,要么引发异常。这样一来,如果你完全返回,你就知道你有有效的场景。
-
我忘了提到在所有场景中返回类型都是 json,实际上我在应用时返回了一个 http 代码和描述,有效的场景与无效的不同,因为是没有消息的 204,字符串只是为了说明我想做的事情,但我有几个 403,只有消息不同
标签: python python-3.x