您可以使用循环:
conditions = (check_size, check_color, check_tone, check_flavor)
for condition in conditions:
result = condition()
if result:
return result
这样做还有一个好处,就是您现在可以使条件数可变。
您可以使用map()
+filter()
(Python 3版本,使用Python 2中的future_builtins
版本)来获取第一个这样的匹配值:
try:
# Python 2
from future_builtins import map, filter
except ImportError:
# Python 3
pass
conditions = (check_size, check_color, check_tone, check_flavor)
return next(filter(None, map(lambda f: f(), conditions)), None)
但是,如果更具可读性,则值得商bat。
conditions = (check_size, check_color, check_tone, check_flavor)
checks = (condition() for condition in conditions)
return next((check for check in checks if check), None)