Python 3.52中的字符串或对象比较

2024-09-29 23:25:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做这件事驱魔.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

Tags: ioselfmakereturniftimedefmore
1条回答
网友
1楼 · 发布于 2024-09-29 23:25:08

没有^{} 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循环和减法。你知道吗

相关问题 更多 >

    热门问题