类对象比较运算符无法工作python

2024-03-28 14:43:30 发布

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

def is_after1(t1, t2):
    """true if t1 follows t2 chronologically"""
    if t1.hour > t2.hour:
        return True
    elif t1.hour == t2.hour:
        if t1.minute > t2.minute:
            return True
    elif t1.hour == t2.hour and t1.minute == t2.minute:
        if t1.second > t2.second:
            return True
    else:
        return False

因此,我尝试在比较后运行一个is廑u,将time作为类“time()”的对象。 但是,当我运行函数时,什么也没有发生。以下是我的函数以及“time”和“time1”的相关值:

^{pr2}$

Tags: 函数truereturniftimeisdeft1
2条回答

您应该打印返回值或将其分配给某个变量,否则返回值将被丢弃。在

print is_after1(time, time1) #prints the returned value

或者:

^{pr2}$

您确实想通过实现special Python hook methods,将您的is_after方法合并到类本身来定义Time()类型的实例如何进行比较。在

一个^{} method将告诉Python两个对象是如何相等的,您可以使用^{}^{}^{}和{a6}钩子来定义排序比较。在

使用^{} class decorator最小化需要实现的方法数:

from functools import total_ordering

@total_ordering
class Time(object):
    def __init__(self, hour, minute, seconds):
        self.hour, self.minute, self.seconds = hour, minute, seconds

    def __eq__(self, other):
        if not isinstance(other, type(self)): return NotImplemented

        return all(getattr(self, a) == getattr(other, a) for a in ('hour', 'minute', 'second'))

    def __lt__(self, other):
        if not isinstance(other, type(self)): return NotImplemented

        if self.hour < other.hour:
            return True
        if self.hour == other.hour:
            if self.minute < other.minute:
                return True
            if self.minute == other.mitune:
                return self.seconds < other.seconds
        return False

现在您只需使用Python<<=>>=和{}运算符直接比较Time()实例

^{pr2}$

相关问题 更多 >