2013-06-30 85 views
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 

所以我試圖運行is_after比較使用時間作爲類「時間()」的對象。 但是,當我運行該功能時,沒有任何反應。這裏是我的功能和「時間」和「時間1」的相關值:類對象比較運算符不工作python

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 

回答

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

你真的要定義Time()類型的實例如何通過實施special Python hook methods,結合您的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