多步骤比较测试

2024-06-02 05:44:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我想实现一个类重载,并得出结论,如果一个给定时间点的事件(例如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

Tags: and方法selftruereturndef时间事件
1条回答
网友
1楼 · 发布于 2024-06-02 05:44:56

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

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)

相关问题 更多 >