定义一个表示时间的类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()
来源:51CTO
作者:Ye硕儿
链接:https://blog.csdn.net/Ye_star/article/details/101223140