【问题标题】:String or object compairson in Python 3.52Python 3.52 中的字符串或对象比较
【发布时间】:2016-10-04 21:06:01
【问题描述】:

我正在做 exorcism.io 时钟练习,但我不知道为什么这个测试失败了。结果看起来完全相同,甚至具有相同的类型。

这是我的代码:

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

【问题讨论】:

  • 您尚未为这些对象定义相等比较,因此它们从object 继承了默认的基于身份的==
  • @user2357112 就是这样。谢谢!还需要将新的小时和分钟放入自字典中。
  • 请不要为您的问题添加解决方案。欢迎您在下面添加您自己的答案。请记住,Stack Overflow 帖子旨在帮助未来有相同问题的访问者,并且答案是独立投票的。

标签: python python-3.x equality


【解决方案1】:

没有__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)

通过为不是Clock 实例(或子类)的东西返回NotImplemented 单例,您可以让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 循环和减法。

【讨论】:

  • 我添加了一个 eq 函数,就像你的建议一样。 main 中的测试现在可以工作,但单元测试仍然失败。 AssertionError: != .
  • @Eman:对,因为它只测试hm 是否完全相等。创建 Clock 实例时,您必须对这些值进行规范化。
  • @Eman:我为此添加了一个建议,将hm 输入标准化为seconds 值。
  • 谢谢,就是这样。当调用 eq 时,我没有考虑到 make_time 没有处理 h 和 m 变量。显示最终代码、附加到问题或回答我自己的问题的最佳方式是什么?
  • @Eman:你不需要展示最终代码;无论如何,未来的访客总是必须根据自己的情况调整答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-16
  • 2019-01-17
  • 1970-01-01
  • 2016-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多