0
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()”类的对象来运行 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
4

2 回答 2

1

你真的想Time()通过实现特殊的 Python 钩子方法来定义类型实例的比较方式,将你的is_after方法合并到类本身中。

一个__eq__方法将告诉 Python 两个对象如何相等,您可以使用、 和__lt__钩子__gt__来定义排序比较。__le____ge__

使用functools.total_ordering类装饰器来最小化您需要实现的方法数量:

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
于 2013-06-30T17:00:31.197 回答
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
于 2013-06-30T16:53:52.860 回答