类对象比较运算符不适用于python

类对象比较运算符不适用于python,python,class,comparison,Python,Class,Comparison,因此,我尝试在比较后运行一个is_,使用time作为类“time()”的对象。 但是,当我运行该函数时,什么也没有发生。以下是我的函数以及“time”和“time1”的相关值: 您应该打印返回值或将其分配给某个变量,否则返回值将被丢弃 is_after1(time, time1) time = Time() time.hour = 12 time.minute = 59 time.second = 30 time1 = Time() time1.hour = 11 time1.minute

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


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

is_after1(time, time1)

time = Time()
time.hour = 12
time.minute = 59
time.second = 30

time1 = Time()
time1.hour = 11
time1.minute = 2
time1.second = 5
或:


您确实希望通过实现定义
Time()
类型的实例的比较方式,将
is\u after
方法合并到类本身中

将告诉Python两个对象如何相等,并且可以使用、和钩子定义排序比较

使用可最小化需要实现的方法的数量:

ret =  is_after1(time, time1) #assings the return value from function to ret 
#do something with ret
print is_after1(time, time1) #prints the returned value
ret =  is_after1(time, time1) #assings the return value from function to ret 
#do something with ret
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
>>> t1 = Time(12, 59, 30)
>>> t2 = Time(11, 2, 5)
>>> t1 < t2
False
>>> t1 >= t2
True