类对象比较运算符不工作python

时间:2013-06-30 16:50:31

标签: python class comparison

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

所以我尝试使用time作为类的对象" Time()"来运行is_after比较。 但是,当我运行该功能时,没有任何反应。这是我的函数以及" 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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

您确实希望通过实施special Python hook methods来定义Time()类型的实例,并将is_after方法合并到类中。

__eq__ method将告诉Python两个对象是如何相等的,您可以使用__lt____gt____le____ge__挂钩来定义排序比较。

使用functools.total_ordering 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()<<=>直接比较>=实例 ==运营商:

>>> t1 = Time(12, 59, 30)
>>> t2 = Time(11, 2, 5)
>>> t1 < t2
False
>>> t1 >= t2
True