class Time(object): def __init__(self, hr, min): self.hr = hr self.min = min def __str__(self): return ‘%d:%d‘ %(self.hr, self.min) __repr__ = __str__ # 重载加法 def __add__(self, other): m = self.min + other.min h = self.hr + other.hr if m>=60: m -= 60 h += 1 if h>=24: h -= 24 return self.__class__(h, m) # 重载‘+=‘方法 def __iadd__(self, other): self.hr += other.hr self.min += other.min if self.min >= 60: self.min -= 60 self.hr += 1 if self.hr >=24: self.hr -= 24 return self
这样就能实现时间的加法。
>> a=Time(3, 6) >> b=Time(20, 52) >> a 3:6 >> a+b 23:58 >> a+=b >>a 23:58
原文地址:https://www.cnblogs.com/00986014w/p/8455845.html
时间: 2024-10-08 11:13:41