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

特別な Python フック メソッドを実装し、メソッドをクラス自体に組み込むことによって、タイプのインスタンスがどのようにTime()比較されるかを定義する必要があります。is_after

__eq__メソッドは、2 つのオブジェクトがどのように等しいかを 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 に答える