时钟类错误处理的最佳方法?

Zuzu

我希望代码停止工作并返回输入时间(小时)等无效,因为它不在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)
让·保罗·卡德隆(Jean-Paul Calderone)

永远不要允许存在无效状态。

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章