我希望代码停止工作并返回输入时间(小时)等无效,因为它不在1到24之间。但是,由于该类的str语句,无效时间仍然会打印出来。无论如何有显示错误而不打印无效时间。
我尝试使用try/except并断言给出错误。
class clock():
def __init__(self,hour, minute, second):
self.hour=hour
self.minute=minute
self.second=second
def __str__(self):
return str (self.hour)+":" + str(self.minute)+":"+str(self.second)
最佳答案
永远不要允许存在无效状态。
class Clock():
def __init__(self, hour, minute, second):
if not (0 <= hour < 24 and 0 <= minute < 60 and 0 <= second < 60):
raise ValueError("Clock values out of bounds")
self.hour = hour
self.minute = minute
self.second = second
关于python - 时钟类错误处理的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64392945/