我有一个类,其中包含如下方法
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场景,所以我想知道是否可能像这样做,我只需要将条件逻辑和条件添加到列表中,然后就可以了。问题是当条件为false时如何获取字符串值。
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风格并推荐的