编程练习:定义一个表示时间的类Time

匿名 (未验证) 提交于 2019-12-03 00:11:01

定义一个表示时间的类Time ,它提供下面操作:
a)Time(hours,minutes,seconds)创建一个对象;
b) t.hours(),t.minutes(),t.seconds()分别 返回时间对象t的小时,分钟和秒值;
c)为Time对象定义加法和减法操作
d)定义时间对象的等于和小于关系运算

代码示例:

class Time:     def __init__(self,hours,minutes,seconds):         self.hours = hours         self.minutes = minutes         self.seconds = seconds     def hours(self):         return self.hours      def minutes(self):         return self.minutes      def seconds(self):         return self.seconds      def __add__(self,another):         hours = ((self.hours*3600 + self.minutes*60 + self.seconds + another.hours*3600 + another.minutes*60 + another.seconds)//3600)         minutes = ((self.hours*3600 + self.minutes*60 + self.seconds + another.hours*3600 + another.minutes*60 + another.seconds - 3600*hours)//60)         seconds = (self.hours*3600 + self.minutes*60 + self.seconds + another.hours*3600 + another.minutes*60 + another.seconds - 60*minutes - 3600*hours)         return Time(hours,minutes,seconds)      def __sub__(self,another):         hours = ((self.hours*3600 + self.minutes*60 + self.seconds - another.hours*3600 - another.minutes*60 - another.seconds)//3600)         minutes = ((self.hours*3600 + self.minutes*60 + self.seconds - another.hours*3600 - another.minutes*60 - another.seconds - 3600*hours)//60)         seconds = (self.hours*3600 + self.minutes*60 + self.seconds - another.hours*3600 - another.minutes*60 - another.seconds - 60*minutes - 3600*hours)         return Time(hours,minutes,seconds)      def __eq__(self,another):         return self.hours*3600 + self.minutes*60 + self.seconds == another.hours*3600 + another.minutes*60 + another.seconds      def __lt__(self,another):         return self.hours*3600 + self.minutes*60 + self.seconds < another.hours*3600 + another.minutes*60 + another.seconds      def print(self):         print(self.hours,"h",self.minutes,"m",self.seconds,"s")  t1 = Time(1,20,33) t2 = Time(2,25,47) t3 = t2 - t1 t4 = t2 + t1 t3.print() t4.print()
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!