【问题标题】:multistep comparison test python多步比较测试python
【发布时间】:2017-07-14 15:40:16
【问题描述】:

我想实现一个类重载并得出结论,如果一个给定时间点的事件(例如 12:59:50)发生在另一个事件之前,所以输出是真还是假,只是一个简单的比较测试。如您所见,我实现了它,但是,我很确定这不是执行任务的最 Python 或更好的面向对象的方法。我是 python 新手,所以有什么改进吗?

谢谢

def __lt__(self, other):
    if self.hour  < other.hour:
       return True 

    elif (self.hour == other.hour) and (self.minute < other.minute):             
        return True

    elif (self.hour == other.hour) and (self.minute == other.minute) and (self.second < other.second):            
        return True

    else:            
        return False

【问题讨论】:

  • 你可以使用datetime

标签: python if-statement comparison multi-step


【解决方案1】:

元组(和其他序列)已经执行了您正在实现的字典比较类型:

def __lt__(self, other):
    return (self.hour, self.minute, self.second) < (other.hour, other.minute, other.second)

operator 模块可以稍微清理一下:

from operator import attrgetter

def __lt__(self, other):
    hms = attrgetter("hour", "minute", "second")
    return hms(self) < hms(other)

【讨论】:

    猜你喜欢
    • 2019-11-07
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多