Python 3.52中的字符串或对象compairson
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python 3.52中的字符串或对象compairson,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1760字,纯文字阅读大概需要3分钟。
内容图文
我正在进行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
解决方法:
没有__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知道另一个对象也可以被要求测试是否相等.
但是,您的代码接受的值大于正常的小时和分钟范围;而不是存储小时和分钟,存储秒数并规范化该值:
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循环并减去.
内容总结
以上是互联网集市为您收集整理的Python 3.52中的字符串或对象compairson全部内容,希望文章能够帮你解决Python 3.52中的字符串或对象compairson所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。