2016-10-04 14 views
3

我正在exorcism.io時鐘練習,我無法弄清楚爲什麼這個測試失敗。結果看起來完全相同,甚至具有相同的類型。在Python 3.52中的字符串或對象compairson

這裏是我的代碼:

class Clock: 
    def __init__(self, h, m): 
     self.h = h 
     self.m = m 
     self.adl = 0 

    def make_time(self): 
     s = self.h * 3600 
     s += self.m * 60 
     if self.adl: s += self.adl 

     while s > 86400: 
      s -= 86400 

     if s == 0: 
      return '00:00' 

     h = s // 3600 

     if h: 
      s -= h * 3600 

     m = s // 60 
     return '{:02d}:{:02d}'.format(h, m) 

    def add(self, more): 
     self.adl = more * 60 
     return self.make_time() 

    def __str__(self): 
     return str(self.make_time()) # i don't think I need to do this 

if __name__ == '__main__': 
    cl1 = Clock(34, 37) #10:37 
    cl2 = Clock(10, 37) #10:37 
    print(type(cl2)) 
    print(cl2, cl1) 
    print(cl2 == cl1) #false 
+1

您還沒有爲這些對象定義一個相等比較,所以它們從'object'繼承了默認的基於標識的'=='。 – user2357112

+0

@ user2357112就是這樣。謝謝!還需要將新的小時和分鐘放在自己的字典中。 – Eman

+0

請不要爲您的問題添加解決方案。歡迎您在下面添加您自己的答案。請記住,堆棧溢出帖子意味着對未來的訪問者有同樣的問題,並且答案是獨立投票的。 –

回答

5

自定義類沒有__eq__ method默認測試身份。也就是說,對這樣的一個類的實例的兩個引用只有在引用它們完全相同的對象時纔是相等的。

你需要自定義一個__eq__方法返回True當兩個實例包含相同的時間:

def __eq__(self, other): 
    if not isinstance(other, Clock): 
     return NotImplemented 
    return (self.h, self.m, self.adl) == (other.h, other.m, other.adl) 

通過返回NotImplemented單的東西是不是Clock實例(或子類) ,你讓Python知道other對象也可以被要求測試是否相等。

但是,您的代碼接受的值大於正常的小時和分鐘範圍;而不是商店小時和分鐘,存儲秒和規範該值:

class Clock: 
    def __init__(self, h, m): 
     # store seconds, but only within the range of a day 
     self.seconds = (h * 3600 + m * 60) % 86400 
     self.adl = 0 

    def make_time(self): 
     s = self.esconds 
     if self.adl: s += self.adl 
     s %= 86400 
     if s == 0: 
      return '00:00' 

     s, h = s % 3600, s // 3600 
     m = s // 60 
     return '{:02d}:{:02d}'.format(h, m) 

    def __eq__(self, other): 
     if not isinstance(other, Clock): 
      return NotImplemented 
     return (self.seconds, self.adl) == (other.seconds, other.adl) 

現在你的兩個時鐘情況下將測試相同的,因爲它們在內部存儲的確切同一時間在一天。請注意,我使用%模數運算符而不是while循環並減去。

+0

我添加了一個eq函數,就像您的建議一樣。 __main__中的測試現在可用,但單元測試仍然失敗。 AssertionError:!= 。 – Eman

+0

@Eman:對,因爲它只測試「h」和「m」是否完全相等。創建「時鐘」實例時,必須對這些值進行規範化。 –

+0

@Eman:我爲此添加了一個建議,將'h'和'm'輸入標準化爲'seconds'值。 –