2016-10-04 15 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'值。 –