我正在做这件事驱魔.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
没有^{} method 的自定义类默认为测试标识。也就是说,两个对此类实例的引用只有在它们的引用完全相同时才相等。你知道吗
您需要定义一个自定义
__eq__
方法,当两个实例包含相同的时间时,该方法返回True
:通过为不是
Clock
实例(或子类)的对象返回NotImplemented
单例,可以让Python知道other
对象也可以被要求测试相等性。你知道吗但是,代码接受的值大于正常的小时和分钟范围;而不是存储小时和分钟,而是存储秒并将该值标准化:
现在您的两个时钟实例将测试相等,因为它们在内部存储一天中完全相同的时间。注意,我使用了
%
模运算符,而不是while
循环和减法。你知道吗相关问题 更多 >
编程相关推荐