python - 根据输入参数的数量具有不同行为的函数
问题描述
我想创建一个函数来检查是否是正确的时间来执行操作,但我希望它灵活并检查作为函数输入的每一对参数的条件。我写了一些代码在理论上应该是什么样子,现在我正试图弄清楚如何在代码中编写它。
def report_time(greater_than1=0, lower_than1=24,
greater_than2=0, lower_than2=24,
greater_than3=0, lower_than3=24,
...
greater_thanN=0, lower_thanN=24):
if greater_than1 < datetime.now().hour < lower_than1:
logger.info('Hour is correct')
return True
if greater_than2 < datetime.now().hour < lower_than2:
logger.info('Hour is correct')
return True
if greater_than3 < datetime.now().hour < lower_than3:
logger.info('Hour is correct')
return True
...
if greater_thanN < datetime.now().hour < lower_thanN:
logger.info('Hour is correct')
return True
使用示例:
foo = report_time(16, 18)
foo = report_time(16, 18, 23, 24)
foo = report_time(16, 18, 23, 24, ..., 3, 5)
解决方案
一个更好的选择是让函数只接受一对参数,然后遍历函数外的所有对,并检查是否在任何步骤 aTrue
被返回:
def report_time(greater_than=0, lower_than=24):
return greater_than < datetime.now().hour < lower_than
start_times = [10, 12, 20]
end_times = [11, 15, 22]
for start, end in zip(start_times, end_times):
if report_time(start, end):
logger.info('Hour is correct')
break
valid_times = map(report_time, start_times, end_times)
if any(valid_times):
logger.info('Hour is correct')
此外,正如@AzatIbrakov 在他对另一个答案的评论中所提到的,如果您使用元组会更好。您可以filter
在这种情况下使用:
def within_limits(limits=(0, 24)):
return limits[0] < datetime.now().hour < limits[1]
time_limits = [(10, 11), (12, 15), (20, 22)]
if any(filter(within_limits, time_limits)):
logger.info('Hour is correct')