import datetime
class Time:
def __init__(self, init_hr = 10, init_min = 30, init_ampm = "AM"):
"""
initializes the hour, the minute, and a string indicating
whether it's an AM or PM time
"""
if init_hr < 1 or init_hr > 12:
raise Exception("Error: Invalid hour for Time object")
if init_min < 0 or init_min > 59:
raise Exception("Error: Invalid minute for Time object")
init_ampm = init_ampm.upper()
if init_ampm != "AM" and init_ampm != "PM":
raise Exception("Error: Invalid am/pm flag for Time object")
self.hr = init_hr
self.min = init_min
self.ampm = init_ampm
def __add__(self, mins):
"""
Returns the sum of a Time instance and a non-negative integer mins
"""
if mins // 60 and self.hr < 12:
div = mins // 60
add = self.hr + div
mod = mins % 60
add2 = self.min + mod
string = Time(add, add2)
return string
elif mins // 60 and self.hr == 12:
div = mins // 60
addsub = self.hr + div - 12
mod = mins % 60
add2 = self.min + mod
string = Time(addsub, add2)
return string
当我测试添加功能时,它给了我这个错误:
Traceback (most recent call last):
File "C:\Python34\problem2.py", line 313, in <module>
print("645 minutes after ", t3, " the time is", t3 + 645)
File "C:\Python34\problem2.py", line 100, in __add__
string = Time(add, add2)
File "C:\Python34\problem2.py", line 18, in __init__
raise Exception("Error: Invalid hour for Time object")
Exception: Error: Invalid hour for Time object
不确定为什么它会给我这个错误,但是在午夜之后,这个错误总会发生。任何解决方案?
答案 0 :(得分:1)
if init_hr&lt; 1或init_hr&gt; 12:条件正在解雇。这是因为add = self.hr + div大于12 ---&#34;午夜后#34;。您可能希望使用模运算符来帮助回绕。似乎你开始计时1.所以...(时间%12)+ 1