下面是自己写的一段时间计算的代码,要求相加,相减,和乘法计算
output如下要求:
the first time interval (fti) is hours=21, minutes=58, seconds=50
the second time interval (sti) is hours=1, minutes=45, seconds=22
the expected result of addition (fti + sti) is 23:44:12
the expected result of subtraction (fti - sti) is 20:13:28
the expected result of multiplication (fti * 2) is 43:57:40
然后问题来了,根据题目要求要用到__str__(self) method, 我现在这段代码只能output后三行,像第一和第二行怎么用__str__来执行?我试过但只能print出一行,还有最后一个乘法的小时怎么变成非标准时间格式,因为用的时间格式都是"%H:%M:%S",所以最后一行小时的显示达不到要求
```python
from datetime import time, datetime
class time_interval:
def __init__(self,hours,minutes,seconds):
self.hours=hours
self.minutes=minutes
self.seconds=seconds
#def __str__(self):
# return "the first time interval (fti) is hours=%d, minutes=%d, seconds=%d"%(self.hours,self.minutes,self.seconds)+"
def __add__(self,others):
x=self.seconds+others.seconds
y=self.minutes+others.minutes
z=self.hours+others.hours
if x > 59:
x = x-60
y += 1
if y > 59:
y = y-60
z += 1
if z > 23:
z = z-24
if y > 59:
y = y-60
z += 1
if z > 23:
z=z-24
if z > 23:
z=z-24
return "the expected result of addition (fti+sti) is "+time(z,y,x).strftime("%H:%M:%S")
def __sub__(self,others):
x=self.seconds-others.seconds
y=self.minutes-others.minutes
z=self.hours-others.hours
if x < 0:
x = 60+x
y -= 1
if y < 0:
y = 60+y
z -= 1
if z < 0:
z = 24+z
if y < 0:
y = 60+y
z -= 1
if z < 0:
z=24+z
if z < 0:
z=z+24
return "the expected result of subtraction (fti-sti) is "+time(z,y,x).strftime("%H:%M:%S")
def __mul__(self,var):
x=self.seconds*var
y=self.minutes*var
z=self.hours*var
if x > 59:
x = x-60
y += 1
if y > 59:
y = y-60
z += 1
if z > 23:
z = z-24
if y > 59:
y = y-60
z += 1
if z > 23:
z=z-24
if z > 23:
z=z-24
return "the expected result of multiplication (fti*2) is "+time(z,y,x).strftime("%H:%M:%S")
p1=time_interval(21,58,50)
p2=time_interval(1,45,22)
print(p1.__add__(p2))
print(p1.__sub__(p2))
print(p1.__mul__(2))
```