【问题标题】:Best possible method of error handling of clock class?时钟类错误处理的最佳方法?
【发布时间】:2021-01-31 04:47:07
【问题描述】:

我希望代码停止工作并返回输入时间(小时)等无效,因为它不在 1-24 之间。然而,由于类的 str 语句,无效时间仍然打印出来。无论如何在不打印无效时间的情况下显示错误。 我尝试使用 try/except 和 assert 来给出错误。

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)

【问题讨论】:

    标签: python python-3.x class error-handling python-class


    【解决方案1】:

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

    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
    

    【讨论】:

      【解决方案2】:

      接受的答案很好,但可以通过更好的错误消息进行一些改进:

      class Clock:
          def __init__(self, hour, minute, second):
              if hour not in range(24):
                  raise ValueError('hour not in range(24)')
              if minute not in range(60):
                  raise ValueError('minute not in range(60)')
              if second not in range(60):
                  raise ValueError('second not in range(60)')
              self.__hour = hour
              self.__minute = minute
              self.__second = second
      
          def __str__(self):
              return f'{self.__hour}:{self.__minute}:{self.__second}'
      

      每当Clock 类使用不正确时,ValueError 都会准确说明问题所在。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-08-21
        • 2017-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-10
        相关资源
        最近更新 更多